[Python] Python 基本指令筆記

字串處理 (String)

判斷是否全為英文字母

s.isalpha()

大/小寫

"string".lower()
"STRING".upper()

字串長度

len(s)


擷取部分字串(類似substring in Java)

s[start_index:end_index]
start_index and end_index is either optional.
ex:
s="abcde"
s[1:4] #取出字元1~3
>>> "bcd"

s[3:] #從字元3開始擷取字串
>>> "de"

s[:4] #從頭開始擷取字串到字元4之前
>>> "abcd"

判斷是否為空字串

if not str #若字串為空,則if成立


陣列


陣列長度

arr=[1,2,5]
len(arr) # len = 3


陣列找元素位置(index)

arr=['a', b, 'c']
print arr.index('b') # 1

陣列插入元素於指定位置

arr=['a', b, 'c']
print arr.insert(2, 'd') # ['a', 'b', 'd', 'c']

排序

arr=[3, 1, 2]
arr.sort() # [1,2,3]


加總 / 平均

arr=[3, 1, 2]

sum(arr) # 6
average(arr) # 6 / 3 = 2


刪除元素

arr=[3, 1, 2]

arr.remove(3) # [1, 2] <- delete the real item if found.
arr.pop(0) # [1, 2] <- delete the item at the index.


Dictionary (Key-Value pair)

讀取數值


dic = {'x': 1, 'y': 2, 'z': 3}
print (dic['x']) # 1

增加元素



dic = {'x': 1, 'y': 2, 'z': 3}
dic['w': 4] # {'x': 1, 'y': 2, 'z': 3, 'w': 4}

刪除元素



dic = {'x': 1, 'y': 2, 'z': 3}
del dic['x'] # {'y': 2, 'z': 3}


for loop 走訪各個元素



dic = {'x': 1, 'y': 2, 'z': 3}
for key in dic:
    print (dic[key])


其他小技巧

range函數製造數列

range(stop)
range(start, stop)
range(start, stop, step)

ex:
range(6) # => [0,1,2,3,4,5]
range(1,6) # => [1,2,3,4,5]
range(1,6,3) # => [1,4]

print裡含有變數


name1 = "Mike"
name2 = "Milly"
print ("Hello %s and %s" % (name1, name2))



循序列印出list裡的元素(用.join連接)


list = ['a', 'b', 'c']
print "--".join(list) # a--b--c

循序列印出list裡的元素(用.join連接)


list = ['a', 'b', 'c']
print "--".join(list) # a--b--c

列印出dictionary裡的元素(key-value pairs)



dict = {'a': 1, 'b': 2, 'c': 3}
print dict.items() # 不一定會按照儲存順序列印

print 在同一行(非分行列印)


for i in range(3):
    print (i), # 012, not 0\n1\n2

dict = {1: 'a', 2: 'b', 3: 'c'}
for key in dict:
    print key, dict[key]

現在時間

from datetime import datetime
now = datetime.now()

print now

# 2017-07-06 16:51:10.144976

year = now.year # 2017
month = now.month # 7
day = now.day # 6
hour = now.hour # 16
minute = now.minute
second = now.second

留言