## 字串的操作 ``` string="my first" print(string.upper()) #字串變大寫 string=string.upper() print(string.isupper()) #判斷字串是否大寫(回傳bool值) string2="my second" print(string + string2) #字串相加印出 print("string + string2")單純印出"string + string2" #print(string[1]) #[x]位置 x=0,1,2... #print(string.index("i")) #找尋字串內項目的位置 #print(string.replace("my","your")) #replcae "my" with "your" ``` ## 數字與運算符號 ``` from math import* #導入模組 number=10 #數字跟字串有區別 #print(10+3) #print(8//3) #整數除法(python預設都是浮點數) #print(round(4.6))#四捨五入 #print(floor(4.6)) #不大於4.6的最大整數 #print(ceil(4.1)) #不小於4.1的最大整數 #number=str(number) #變字串\ #print(3+number) #會錯誤,數字跟字串不能相加 print(max(3,44,67,3,5,77,23)) #尋找最大值 ``` ## 列表list ``` a = ['apple','banana','orange'] #字串的串列 b = [1,2,3,4,5] #數字的串列 c = ['apple',1,2,3,['dog','cat']] #也可以混在一起 print(type(a)) string="abc" d=list() #創建空list D=[] #創建空list e=list(string) #串列化 #如果為字串,會自動拆開成字元 print(e) #["a","b","c"] a.extend(b) #將串列連接起來 print(a) #['apple', 'banana', 'orange', 1, 2, 3, 4, 5] print(b[0]) #讀取串列值,[index=0,1,2,3...] print(b[-1]) #從後方開始算 print(b[:2:1]) #slice #從0取到index=1的位置,間隔為1 #注意[0:2]並不包括index=2 f=b #list複製 f[0]=2 print(b) #如果指接用f=b指派的方式,原本b也會一併被改變 print(f) #print(b)==print(f) g=b[:] #後面加上[:]來複製list,不會更改到原本list g[0]=99 print(g) #[99, 2, 3, 4, 5] print(b) #[1, 2, 3, 4, 5] b.append(99) #在list後面增加() print(b) #[1, 2, 3, 4, 5, 99] b.insert(6,100) #insert(A,B)在index A插入B值 print(b) #[1, 2, 3, 4, 5, 99, 100] del b[0] #delete "特定index" print(b) #[2, 3, 4, 5, 99, 100] b.remove(100) #如果不知道index, remove delete"特定項目值" print(b) #[2, 3, 4, 5, 99] num=b.pop(99) #取出"特定項目值" (有回傳) print(num) ``` ## 元組tuple ``` tuple1=(30,44,25,13,1) #元組 ->cannot be changed #tuple[1]=12 #makes no change list0=["a","b","c"] tuple0=tuple(list0) #變成tuple print(tuple0) print(tuple0[0]) #print "a" print(tuple0[1]) #print "b" print(tuple0[2]) #print "c" print(tuple0+tuple1) #tuple合併 ('a', 'b', 'c', 30, 44, 25, 13, 1) print(tuple1*3) #tuple內容重複n次(30, 44, 25, 13, 1, 30, 44, 25, 13, 1, 30, 44, 25, 13, 1) ``` ## 集合set ``` fruits={"apple","grape","orange","orange"} #set by using big parenthesis which is unordered,unindexed,no copied elements print(fruits) #print in random orders everytimes and "orange" just present once list0=[1,2,3,4,5] tuple0=("a","b","c") set0=set(list0) #變成set set1=set(tuple0) #變成set fruits.add("") #set 中增加 fruits.remove("") #從set中移出 fruits.clear() #清空 vegatable={"tomato","corn"} fruits.update(vegatable) #結合兩個set\ food=fruits.union(vegatable) #取聯集 print(food.difference(fruits)) #取差集,print tomato,corn print(food.intersection(fruits)) #取交集 print fruit{} print(food.symmetric_difference(fruits)) #取對稱差集 ```