1. 程式人生 > >python 還不是大全的小問題

python 還不是大全的小問題

world 字符轉換 div real creat tps hello == -a

1.pythone 獲取系統時間
import datetime
nowTime=datetime.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S‘)#現在
pastTime = (datetime.datetime.now()-datetime.timedelta(hours=1)).strftime(‘%Y-%m-%d %H:%M:%S‘)#過去一小時時間
afterTomorrowTime = (datetime.datetime.now()+datetime.timedelta(days=2)).strftime(‘%Y-%m-%d %H:%M:%S‘)#後天
tomorrowTime = (datetime.datetime.now()+datetime.timedelta(days=1)).strftime(‘%Y-%m-%d %H:%M:%S‘)#明天
print(‘\n‘,nowTime,‘\n‘,pastTime,‘\n‘,afterTomorrowTime,‘\n‘,tomorrowTime)

2.格式化輸出
str="%s:%d"%("hello-world", 123)

 3.if else

 x = int(input("Please enter an integer: "))
 if x < 0:
     x = 0
      print(‘Negative changed to zero‘)
 elif x == 0:
      print(‘Zero‘)
 elif x == 1:
      print(‘Single‘)
 else:
      print(‘More‘)

 4.字符串包含

第一種方法:in

string = ‘helloworld‘

if ‘world‘ in string:

  print ‘Exist‘

else:

  print ‘Not exist‘

第二種方法:find

string = ‘helloworld‘

if string.find(’world‘) == 5: #5的意思是world字符從那個序開始,因為w位於第六個,及序為5,所以判斷5

  print ‘Exist‘

else:

  print ‘Not exist‘

第三種方法:index,此方法與find作用類似,也是找到字符起始的序號

if string.index(’world‘) > -1: #因為-1的意思代表沒有找到字符,所以判斷>-1就代表能找到

  print ‘Exist‘

如果沒找到,程序會拋出異常

  5.字符串分割

st0= ‘iisongiiihuaniiiigongi‘
print(st0.split(‘i‘))
結果為:
[‘‘, ‘‘, ‘song‘, ‘‘, ‘‘, ‘huan‘, ‘‘, ‘‘, ‘‘, ‘gong‘, ‘‘]

  6.python 不支持switch

  查看Python官方:PEP 3103-A Switch/Case Statement, 實現Switch Case需要被判斷的變量是可哈希的和可比較的,

  與Python倡導的靈活性有沖突。在實現上,優化不好做,可能到最後最差的情況匯編出來跟If Else組是一樣的。

  Python沒有支持switch。

 7.python 實現結構體
應用場景:在類中只用globa引用外部的多個變量
# filename:p.py
class Employee:
    pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = ‘John Doe‘
john.dept = ‘computer lab‘
john.salary = 1000
>>> import p
>>> p.john
<p.Employee instance at 0xb71f50ac>
>>> p.john.name
‘John Doe‘
>>> p.john.dept
‘computer lab‘
>>> p.john.salary
1000

  8.轉換

int(x [,base ])         將x轉換為一個整數    
long(x [,base ])        將x轉換為一個長整數    
float(x )               將x轉換到一個浮點數    
complex(real [,imag ])  創建一個復數    
str(x )                 將對象 x 轉換為字符串    
repr(x )                將對象 x 轉換為表達式字符串    
eval(str )              用來計算在字符串中的有效Python表達式,並返回一個對象    
tuple(s )               將序列 s 轉換為一個元組    
list(s )                將序列 s 轉換為一個列表    
chr(x )                 將一個整數轉換為一個字符    
unichr(x )              將一個整數轉換為Unicode字符    
ord(x )                 將一個字符轉換為它的整數值    
hex(x )                 將一個整數轉換為一個十六進制字符串    
oct(x )                 將一個整數轉換為一個八進制字符串   
chr(65)=‘A‘
ord(‘A‘)=65
int(‘2‘)=2;
str(2)=‘2‘

  9.創建文件服務器

    執行命令python -m SimpleHTTPServer 端口號, 不填端口號則默認使用8000端口。

 

python 還不是大全的小問題