列表與元組
列表用大括號[]表示,元組用圓括號()表示。
列表可以修改,字符串與元組不可修改。
元組的分片還是元組,列表的分片還是列表。
1.列表方法:
name=["zhang3","li4","wang5"]name.append("gou6") #添加項(xiàng)name.remove("gou6") #移除第一個匹配項(xiàng),也可用del name[3]來移除name.insert(3,"gou6") #插入項(xiàng)name.index("gou6") #找出第一個匹配項(xiàng)的位置name.extend(["gou6","xuan7"]) #擴(kuò)展name.pop(0) #返回列表的第一項(xiàng)值并從列表中刪除之2.列表函數(shù):
>>> a=list("hi guys") #把字符串轉(zhuǎn)換為列表>>> print a['h', 'i', ' ', 'g', 'u', 'y', 's']>>> ''.join(a) #把列表還原成字符串'hi guys'>>> max(a) #取得列表的最大元素'y'>>> len(a) #取得列表長度7>>> min(a) #取得最小元素' '>>> tuple(a) #將列表轉(zhuǎn)換為元組('h', 'i', ' ', 'g', 'u', 'y', 's')>>> sorted(a) #將列表元素排序[' ', 'g', 'h', 'i', 's', 'u', 'y']3.列表遍歷:
A,使用for語句遍歷
for each_item in name: print(each_item)
B,使用while語句遍歷
i=0while i < len(name): print(name[i]) i += 1
4.成員資格1:
>>> sub="hello, you are a bear">>> "bear" in subTrue>>> "y" in subTrue>>> raw_input("what's your name?") in subwhat's your name?bearTrue5.成員資格2:
database=[["zhang3","0111"],["li4","0112"],["wang5","0113"]]username=raw_input("what's your user name?")id=raw_input("what's your id?")if [username,id] in database: print "access granted"6.找出10以內(nèi)的整數(shù)
s = [x for x in range(0, 10) if x % 2 == 0]
7.生成九九乘法表
s = [(x, y, x*y) for x in range(1, 10) for y in range(1,10) if x>=y]
字符串
1.獲取字符串
name=raw_input("what's your name?") print "Hello," + name + ".welcome to us"注意:Pyhton3.x版本取消了raw_input,統(tǒng)一使用input
輸出值:
print name + repr(x)#str用于把值轉(zhuǎn)換為合理的字符串,repr創(chuàng)建一個字符串,返回值的字符串形式#str是一種類型(和int一樣),repr是函數(shù)
2.換行符用/n表示
原始字符串,以字符串前加一個r即可,如
print r"c:/nowindows/no"path="c:/nowindows/no"; print repr(path)
3.Unicode字符串
print u"redhat"
注意:Pyhton3.x版本所有字符串都是unicode字符串
定義字符串時,雙引號和單引號都是可以用的,只不過用單引號的時候可以在字符串里面使用雙引號
布爾值:
>>> bool('i love you')True>>> bool(42)True>>> bool(1)True>>> bool('0')True>>> bool(0)False>>> bool('')False4.字符串方法
>>> tag="<a href=http://www.baidu.com>baidu indexpage</a>">>> print tag[8:28] #字符串分片http://www.baidu.com>>> print tag[29:-4] #字符串分片baidu indexpage>>> tag.replace("www.baidu.com","home.sina.com") #字符串替換'<a href=http://home.sina.com>baidu indexpage</a>'>>> dirs=["","usr","bin","env"]>>> "/".join(dirs) #將列表拼接成字符串'/usr/bin/env'>>> print ("C:" + "http://".join(dirs))C:/usr/bin/env>>> path="/usr/bin/env">>> path.split("/") #將字符串分割成列表['', 'usr', 'bin', 'env']5.其它字符串方法
>>> s=' I Love you! '>>> s.lower() #轉(zhuǎn)換字符串的小寫' i love you! '>>> s.upper() #轉(zhuǎn)換字符串的大寫' I LOVE YOU! '>>> s.title() #換換字符串為標(biāo)題(所有單詞首字母大寫)' I Love You! '>>> s.islower() #判斷字符串是否為小寫(也可判斷大寫和標(biāo)題)False>>> s.strip() #去除首尾空格,lstrip去除左邊空格,rstrip去除右邊空格'I Love you!'>>> word=s.split() #分割>>> word['I', 'Love', 'you!']>>> '::'.join(word) #合并'I::Love::you!'>>> s.count('o') #統(tǒng)計(jì)出現(xiàn)次數(shù)2>>> s.find('you') #查找位置,如果找不到,則返回-19>>> s.startswith('python')False>>> s.replace('you','yours')' I Love yours! '新聞熱點(diǎn)
疑難解答
圖片精選