列表與元組
列表用大括號[]表示,元組用圓括號()表示。
列表可以修改,字符串與元組不可修改。
元組的分片還是元組,列表的分片還是列表。
1.列表方法:
name=["zhang3","li4","wang5"] name.append("gou6") #添加項 name.remove("gou6") #移除第一個匹配項,也可用del name[3]來移除 name.insert(3,"gou6") #插入項 name.index("gou6") #找出第一個匹配項的位置 name.extend(["gou6","xuan7"]) #擴展 name.pop(0) #返回列表的第一項值並從列表中刪除之
2.列表函數:
>>> a=list("hi guys") #把字符串轉換為列表 >>> print a ['h', 'i', ' ', 'g', 'u', 'y', 's'] >>> ''.join(a) #把列表還原成字符串 'hi guys' >>> max(a) #取得列表的最大元素 'y' >>> len(a) #取得列表長度 7 >>> min(a) #取得最小元素 ' ' >>> tuple(a) #將列表轉換為元組 ('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=0 while i < len(name): print(name[i]) i += 1
4.成員資格1:
>>> sub="hello, you are a bear" >>> "bear" in sub True >>> "y" in sub True >>> raw_input("what's your name") in sub what's your name"jb51code">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以內的整數
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,統一使用input
輸出值:print name + repr(x) #str用於把值轉換為合理的字符串,repr創建一個字符串,返回值的字符串形式 #str是一種類型(和int一樣),repr是函數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:" + "\\".join(dirs)) C:\usr\bin\env >>> path="/usr/bin/env" >>> path.split("/") #將字符串分割成列表 ['', 'usr', 'bin', 'env']5.其它字符串方法
>>> s=' I Love you! ' >>> s.lower() #轉換字符串的小寫 ' i love you! ' >>> s.upper() #轉換字符串的大寫 ' I LOVE YOU! ' >>> s.title() #換換字符串為標題(所有單詞首字母大寫) ' I Love You! ' >>> s.islower() #判斷字符串是否為小寫(也可判斷大寫和標題) False >>> s.strip() #去除首尾空格,lstrip去除左邊空格,rstrip去除右邊空格 'I Love you!' >>> word=s.split() #分割 >>> word ['I', 'Love', 'you!'] >>> '::'.join(word) #合並 'I::Love::you!' >>> s.count('o') #統計出現次數 2 >>> s.find('you') #查找位置,如果找不到,則返回-1 9 >>> s.startswith('python') False >>> s.replace('you','yours') ' I Love yours! '
Tags:文章來源: