python基礎2
python基礎2
####字符串的基本操作###
字符串切片:
>>> s = ‘hello‘
>>> s[2:5]
‘llo‘
>>> s[0:5]
‘hello‘
>>> s[3:]
‘lo‘
>>> s[:3]
‘hel‘
>>> s[0:3:2]
‘hl‘
>>>
如果只有[:],則表示全部
字符串操作
In [1]: s = ‘hello‘
In [2]: type(s)
Out[2]: str
In [4]: s.
s.capitalize s.format s.isupper s.rindex s.strip
s.center s.index s.join s.rjust s.swapcase
s.count s.isalnum s.ljust s.rpartition s.title
s.decode s.isalpha s.lower s.rsplit s.translate
s.encode s.isdigit s.lstrip s.rstrip s.upper
s.endswith s.islower s.partition s.split s.zfill
s.expandtabs s.isspace s.replace s.splitlines
s.find s.istitle s.rfind s.startswith
In [4]: s.capitalize()###將第一個轉換成大寫字母###
Out[4]: ‘Hello‘
In [5]: help (s.capitalize)###查看幫助,按q退出###
In [6]: help(s.c)
s.capitalize s.center s.count
In [6]: help(s.center)###給一個寬度,如果字符串小於該寬度,就會自動填充,默認使用空格,如果傳遞的參數,除了數字還有字符,則會使用該字符填充,返回值為srt
例:
In [16]: s.center(10,‘#‘)
Out[16]: ‘##hello###‘
In [17]: s.center(10)
Out[17]: ‘ hello ‘
In [18]:
###字符串的其他操作###
In [18]: s.
s.capitalize s.format s.isupper s.rindex s.strip
s.center s.index s.join s.rjust s.swapcase
s.count s.isalnum s.ljust s.rpartition s.title
s.decode s.isalpha s.lower s.rsplit s.translate
s.encode s.isdigit s.lstrip s.rstrip s.upper
s.endswith s.islower s.partition s.split s.zfill
s.expandtabs s.isspace s.replace s.splitlines
s.find s.istitle s.rfind s.startswith
In [18]: "WORD".isupper()###判斷是否為大寫,返回值為bool類型
Out[18]: True
In [19]: "2l".isalnum()###數字和字母###
Out[19]: True###返回bool值為true####
In [20]: "2l-".isalnum()
Out[20]: False
In [23]: "Wojfh".isalpha()###字母###
Out[23]: True
In [24]: "234".isdigit()###數字###
Out[24]: True
In [25]: "ldsjfkai".islower()###小寫字母###
Out[25]: True
In [26]: " ".isspace()###空格###
Out[26]: True
In [27]: " d ".isspace()
Out[27]: False
In [28]: "Heloo".istitle()###開頭為大子字母###
Out[28]: True
In [29]: help(s.isupper)###查看幫助###
Help on built-in function isupper:
In [29]:isupper(...)
S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
(END)
####導入模塊srting###
srting.digits
string.letters
In [33]: import string
In [34]: string.digits
Out[34]: ‘0123456789‘
In [35]: string.letters
Out[35]: ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘
編寫程序:判斷輸入的字符串是否符合變量的規則
import string
print "please input a string:"
a = raw_input()
if a[0] in string.letters + "_":
for a in a[1:]:
if a not in string.letters+string.letters+"_":
print "faluse"
exit(1)
print "true"
else:print "faluse"
In [48]: s = " hello "
In [49]: s.strip()###屏蔽前後的空格###
Out[49]: ‘hello‘
In [50]: s.lstrip()###屏蔽左邊的空格###
Out[50]: ‘hello ‘
In [51]: s.rstrip()###屏蔽右邊的空格###
Out[51]: ‘ hello‘
In [52]: s = "hel lo" ###中間的空格不能屏蔽###
In [54]: s.strip()
Out[54]: ‘hel lo‘
In [56]: ip = "172.25.254.12"
In [57]: ip.split(‘.‘)###指定分隔符為".",默認為空格###
Out[57]: [‘172‘, ‘25‘, ‘254‘, ‘12‘]
In [59]: "user1:x:1001:1001::/home/user1:/bin/bash".split(":")
Out[59]: [‘user1‘, ‘x‘, ‘1001‘, ‘1001‘, ‘‘, ‘/home/user1‘, ‘/bin/bash‘]
In [61]: "user1:x:1001:1001::/home/user1:/bin/bash".endswith("bash")###以bash結尾###
Out[61]: True
In [62]: "user1:x:1001:1001::/home/user1:/bin/bash".startswith("user1")###以user1開頭###
Out[62]: True
In [63]: s.lower()###轉換成小寫字母###
Out[63]: ‘hel lo‘
In [64]: s.upper()###轉換成大寫字母###
Out[64]: ‘HEL LO‘
In [65]: s = ‘hElO‘
In [66]: s.swapcase()###將大寫轉換成小寫,小寫轉換成大寫###
Out[66]: ‘HeLo‘
練習:要求用戶輸入一個英文句子,統計該英文句子中含有單詞的數目
測試:輸入:i like python very much
輸出:5
a = raw_input("請輸入一個英文句子:")
lengthen = len(a.split())###字符串計算長度:len()可以統計分隔數目###
print lengthen
測試:
請輸入一個英文句子:i like python very much
5
import string
alphas = string.letters
nums = string.digits
print "歡迎進入變量檢測系統V1.0".center(50,"*")
print ‘Test string must be at least 1 char long‘
variable = raw_input("輸入檢測的變量名:")
if len(variable) > 0:
if variable[0] not in alphas:
print ‘變量名必須為字母或下劃線開頭‘
else:
for ochar in variable[1:]:
if ochar not in alphas + nums:
print ‘無效的變量名‘
exit(1)
print ‘%s 變量名合法‘ % variable
else:
print ‘變量名長度必須大於0‘
#####列表#####
列表中的元素可以是任意類型,列表,字符串均可
In [67]: li = []###定義一個空列表###
In [68]: type(li)
Out[68]: list
In [70]: li = ["fentiao",5, "male"]###列表中的元素可以是任意類型,列表,字符串,數字均可
####列表的索引與切片###
In [71]: li[1]###索引###
Out[71]: 5
In [73]: li[0]
Out[73]: ‘fentiao‘
In [74]: li[2]
Out[74]: ‘male‘
In [75]: li[0:2]###切片###
Out[75]: [‘fentiao‘, 5]
In [76]: li[:]###全部###
Out[76]: [‘fentiao‘, 5, ‘male‘]
In [77]: li
Out[77]: [‘fentiao‘, 5, ‘male‘]
In [78]: len(li)###查看幾個元素###
Out[78]: 3
In [79]: "fentiao" in li###查看fentiao是否在li列表中###
Out[79]: True
In [80]: "fendai" in li
Out[80]: False
In [81]: li1 = [1,2,3]+[2,3,4]###連接兩個列表###
In [82]: print li1
[1, 2, 3, 2, 3, 4]
In [83]: li3 = li*3###重復三次###
In [84]: print li3
[‘fentiao‘, 5, ‘male‘, ‘fentiao‘, 5, ‘male‘, ‘fentiao‘, 5, ‘male‘]
In [85]: li = [‘fentiao‘,7,‘male‘,[‘westos‘,‘redhat‘,‘linux‘]]###列表中可以在嵌套列表###
In [86]: li[3][2]###查詢列表中的列表的元素##
Out[86]: ‘linux‘
In [87]: li[3]
Out[87]: [‘westos‘, ‘redhat‘, ‘linux‘]
In [88]: li.
li.append li.extend li.insert li.remove li.sort
li.count li.index li.pop li.reverse
In [89]: li.append("hello")###在列表中添加hello,默認添加在末尾###
In [90]: print li
[‘fentiao‘, 7, ‘male‘, [‘westos‘, ‘redhat‘, ‘linux‘], ‘hello‘]
In [91]: li.insert(0,‘hel‘)###在索引0前添加hel###
In [92]: print li
[‘hel‘, ‘fentiao‘, 7, ‘male‘, [‘westos‘, ‘redhat‘, ‘linux‘], ‘hello‘]
In [93]: li.
li.append li.extend li.insert li.remove li.sort
li.count li.index li.pop li.reverse
In [93]: help(li.extend)
In [94]:
In [95]: li.extend(‘hel‘)###添加多個元素###
In [96]: li
Out[96]:
[‘hel‘,
‘fentiao‘,
7,
‘male‘,
[‘westos‘, ‘redhat‘, ‘linux‘],
‘hello‘,
‘h‘,
‘e‘,
‘l‘]
In [97]: li = [‘hwllo‘,2,3,‘hao‘]
In [98]: li
Out[98]: [‘hwllo‘, 2, 3, ‘hao‘]
In [99]: li.extend([‘hello‘,‘world‘])###將hello,world,添加到列表中###
In [100]: li
Out[100]: [‘hwllo‘, 2, 3, ‘hao‘, ‘hello‘, ‘world‘]
In [101]: li[0]
Out[101]: ‘hwllo‘
In [102]: li[0] = ‘fentiao‘###列表中的元素是可變的,因此可修改列表中的元素,直接賦值,###
In [103]: li
Out[103]: [‘fentiao‘, 2, 3, ‘hao‘, ‘hello‘, ‘world‘]
In [104]: li.count(‘hao‘)###統計hao出現的次數###
Out[104]: 1
In [105]: li.count(‘fentiao‘)
Out[105]: 1
In [106]: li.count(‘fendai‘)
Out[106]: 0
In [107]: li.insert(2,‘hello‘)
In [108]: li
Out[108]: [‘fentiao‘, 2, ‘hello‘, 3, ‘hao‘, ‘hello‘, ‘world‘]
In [109]: li.count(‘hello‘)
Out[109]: 2
In [110]: li.index(‘fentiao‘)###查看fentiao的索引###
Out[110]: 0
In [111]: li.index(2)
Out[111]: 1
In [113]: li.index(‘hello‘)
Out[113]: 2
In [114]: li.re
li.remove li.reverse
In [114]: li.remove("hello")###刪除hello###
In [115]: li
Out[115]: [‘fentiao‘, 2, 3, ‘hao‘, ‘hello‘, ‘world‘]
In [116]: li.remove(li[3])###刪除li[3]對應的元素###
In [117]: li
Out[117]: [‘fentiao‘, 2, 3, ‘hello‘, ‘world‘]
In [118]: li.pop()###彈出,默認彈出最後一個###
Out[118]: ‘world‘
In [119]: li.pop(3)###彈出索引為3的元素###
Out[119]: ‘hello‘
In [120]: li
Out[120]: [‘fentiao‘, 2, 3]
In [121]: li.pop()
Out[121]: 3
In [122]: li.pop()
Out[122]: 2
In [123]: li.pop()
Out[123]: ‘fentiao‘
In [124]: li
Out[124]: []
In [125]: li.pop()
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-125-bdc59cbfe7c0> in <module>()
----> 1 li.pop()
IndexError: pop from empty list
In [126]: de
%%debug %debug def del delattr
In [126]: del li###刪除列表###
In [127]: li
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-127-5ce4e85ef0aa> in <module>()
----> 1 li
NameError: name ‘li‘ is not defined
In [128]:
練習:編寫程序實現stack
####元組###
In [137]: t = (1,2,3,4)###定義元組用()###
In [138]: t[0]###索引###
Out[138]: 1
In [139]: t[2]
Out[139]: 3
In [140]: t[-1]
Out[140]: 4
In [141]: t[:]###切片###
Out[141]: (1, 2, 3, 4)
In [142]: t[1:3]
Out[142]: (2, 3)
In [143]: t(0)=10###不可以對元組進行修改###
File "<ipython-input-143-a7946ca4067e>", line 1
t(0)=10
SyntaxError: can‘t assign to function call
In [144]: name,age,gender=(‘fentiao‘,5,‘male‘)###元組可以多個賦值###
In [145]: print name,age,gender
fentiao 5 male
In [146]: a,b,c = 1,2,3
In [147]: print a,b,c
1 2 3
In [148]: a,b,c = (1,2,3)
In [149]: print a,b,c
1 2 3
In [150]: a=(1)
In [151]: type(a)
Out[151]: int
In [152]: a=("hello")
In [153]: type(a)
Out[153]: str
In [154]: a=("hello",)###如果要定義單個元組,需要加逗號###
In [155]: type(a)
Out[155]: tuple
In [156]: t = (1,2,(1,2),[1,2])###元組裏的元素類型可以是多種的###
In [157]: type(t)
Out[157]: tuple
In [158]: t[3][1]=10###可以對元組的類型為列表的元素賦值###
In [159]: t
Out[159]: (1, 2, (1, 2), [1, 10])
In [161]: t = (1,2,3)*3
In [162]: t
Out[162]: (1, 2, 3, 1, 2, 3, 1, 2, 3)
In [163]: t1 = (‘hello‘,‘world‘)
In [164]: t2 = (‘westos‘,‘linux‘)
In [165]: print t1+t2
(‘hello‘, ‘world‘, ‘westos‘, ‘linux‘)
######集合###
a = raw_input("請輸入一個英文句子:")
b = a.split()
lengthen = len(b)
print lengthen
c = set(b)
lengthen = len(c)
print lengthen
list1 = [1,2,3,4,1,2,3]
s1 = set(list1)
print s1
# print type(list1),type(s1)
s2 = {1,2,100,‘hello‘}
print s1.union(s2)###s1與s2的並集###
print s1.intersection(s2)###s1與s2的交集###
s1.intersection_update(s2)###將s1與s2的交集更新給s1###
print s1
print s1.difference(s2)###差集###
print s1.symmetric_difference(s2)###對等差分###
python基礎2