Python基礎知識(六)--字符串

 

  1. #字符串  
  2.  
  3. #字符串是用固定的str數據類型表示的,用來存放Unicode字符序列  
  4. #str數據類型可以用來創建一個字符串對象,參數爲空時返回一個空字符串  
  5. a = str()  
  6. print(a)                        #  
  7. a = str("abcdef")  
  8. print(a)                        #abcdef  
  9. #str()函數可以用來進行類型轉換  
  10. a = str(123)  
  11. print(a)                        #123  
  12. #字符串是使用引號創建的,可以使用雙引號,也可以使用單引號,  
  13. #字符串兩端所用引號必須相同  
  14. #還可以使用三引號包含的字符串,這是Python對兩端都使用三個引號的字符串的叫法  
  15. text = """A triple quoted string like this can include 'quotes' and  
  16. "quotes" without formality. We can also escape newlines \  
  17. so this particular string is actually only two lines long.""" 
  18. #如果字符串中使用的引號與包含字符串所用引號不同時,  
  19. #可以直接使用,如果相同時,需要進行轉義  
  20. a = "Single 'quotes' are fine; \"doubles\" must be escaped." 
  21. b ='single \'quotes\' must be escaped; "doubles" are fine.' 
  22.  
  23. #在三引號內可以直接使用換行,通過\n可以在任何字符串中包含換行  
  1. #Python字符串轉義  
  2. \newline            #忽略換行?  
  3. \\                  #反斜槓  
  4. \'                  #單引號  
  5. \"                  #雙引號  
  6. \a                  #ASCII蜂鳴 (BEL)  
  7. \b                  #ASCII退格(BS)  
  8. \f                  #ASCII走紙(FF)  
  9. \n                  #ASCII換行(LF)  
  10. \n{name}            #給定名稱的Unicode字符  
  11. \ooo                #給定八進制的字符  
  12. \r                  #ASCII回國符(CR)  
  13. \t                  #ASCII製表符(TAB)  
  14. \uhhhh              #給定16位十六進制的Unicode字符  
  15. \Uhhhhhhhh          #給定32位十六進制的Unicode字符  
  16. \v                  #ASCII垂直指標(VT)  
  17. \xhh                #給定8位十六進制的Unicode字符 
  1. #在使用正則表達式的時候,由於需要使用大量字面意義反斜槓,  
  2. #由於每個反斜槓都需要進行轉義處理,從而造成了不便:  
  3. import re  
  4. phone1 = re.compile("^((?:[(}\\d+[)])?\\s*\\d+(?:-\\d+)?)$")  
  5. #解決的方法是使用原始字符串  
  6. #這種引號或三引號包含的字符串的第一個引號由r引導  
  7. phone2 = re.compile(r"((?:[(}\d+[)])?\s*\d+(?:-\d+)?)$")  
  8.  
  9. #如果有一個長字符串跨越了兩行或更多行,但不使用三引號包含,有兩種方法:  
  10. t = "This is not the best way to join two long strings " + \  
  11.     "together since it relies on ugly newline escaping" 
  12.       
  13. s = ("this is the nice way to join two long strings" 
  14.      "together; it relies on string literal concatenation.")  
  15. #第二種情況,用圓括號將其包含在一起,構成一個單獨的表達式,  
  16. #如果不使用圓括號就只會對第一個字符串賦值,  
  17. #第二個字符串會引起IndentationError異常  
  18.  
  19. #.py文件默認使用UTF-8 Unicode編碼,因此可以寫入任何Unicode字符  
  20. #(這點我就遇到過問題,出現SyntaxError: Non-UTF-8 code)難道是Eclipse搞的鬼?)  
  21. #(改變文件編碼可以解決這個問題)  
  22. #(但IDLE支持倒是真的)  
  23. euros = "€\N{euro sign}\u20AC\U000020AC" 
  24.                           #Unicode字符非大小寫敏感  
  25. print(euros)              #€€€€  
  26. #而且連標誌符也可以  
  27. 姓名 = "張小三" 
  28. print(姓名)               #張小三  
  29. #也就是說支持中文變量名的,雖然這樣用的人很少,但我倒是覺得以後可以這麼試試了  
  30. #如果想知道字符串中某個字符的Unicode字元,可以用內置的ord()函數  
  31. print(ord(euros[0]))      #8364  
  32. print(hex(ord(euros[0]))) #0x20ac  
  33. #同樣,也可以用表示有效字元的任意整數轉換成Unicode字符  
  34. #這需要使用內置chr()函數  
  35. s = "anarchists are " + chr(8734) + chr(0x23B7)  
  36. print(s)                        #anarchists are ∞⎷  
  37. print(ascii(s))                 #'anarchists are \u221e\u23b7'  

 

  1. #比較字符串  
  2. #字符串支持的比較運算符包括:< <= == != > >=  
  3. #對於使用Unicode的字符串,比較運算存在兩個問題:  
  4. #1.字符可以有三種不同的UTF-8編碼字節的表示方式  
  5. #  解決方法導入unicodedata模塊  
  6. #  以"NFKD"爲第一個參數,調用unicodedata.normalize()  
  7. #  該函數返回的UTF-8編碼字節表示的字符串總是字節序列  
  8. #2.有些字符的排序是特定於某種語言的,而有些字符並不具備有意義的排序位置  
  9.  
  10.  
  11. #字符串分片與步距  
  12. #序列中的單個數據或字符串中的單個字符可以用數據項存取操作符[]來提取  
  13. #索引值從0開始,直到字符串長度-1  
  14. #負索引值最後一個字符爲-1,向前逐漸遞減  
  15. #存取超過索引範圍的字符會產生IndexError  
  16. #分片操作符的語法格式  
  17. #seq[start:]                        #提取star開始到字符串結尾  
  18. #seq[start:end]                     #提取start到end-1的字符串  
  19. #seq[start:end:step]                #提取start到end-1的字符串,每次間隔step  
  20. text = "abcdefghijklmnopqrstuvwxyz" 
  21. print(text[0])                      #a  
  22. print(text[0:])                     #abcdefghijklmnopqrstuvwxyz  
  23. print(text[2:10])                   #cdefghij  
  24. print(text[:20])                    #abcdefghijklmnopqrst  
  25. print(text[::2])                    #acegikmoqsuwy  
  26. print(text[10::2])                  #kmoqsuwy  
  27. print(text[10:26:2])                #kmoqsuwy  
  28. print(text[26::-1])                 #zyxwvutsrqponmlkjihgfedcba  
  29. print(text[::-1])                   #zyxwvutsrqponmlkjihgfedcba  
  30.  
  31. #字符串操作符與方法  
  32. #字符串是固定序列,所有用於固定序列的功能都可用於字符串  
  33. #包括in進行成員關係測試,+=進行追加操作  * 進行復制  *= 進行增加的複製  
  34. subtext = "def" 
  35. print(subtext in text)              #True  
  36. subtext += "ghi" 
  37. print(subtext)                      #defghi  
  38. subtext *= 3 
  39. print(subtext)                      #defghidefghidefghi 

 

  1. #字符串方法  
  2. #--------------------------------------------------------------------  
  3. s.capitalize()          #返回字符串s的副本,並將首字符大寫  
  4. text = "this is a test text" 
  5. print(text.capitalize())            #This is a test text  
  6. #--------------------------------------------------------------------  
  7. s.center(width, char)   #返回一個長度爲width的字符串  
  8.                         #字符串s在返回字符串的中間位置  
  9.                         #其餘部份用char添充,char默認爲空格  
  10. s = "abd" 
  11. print(s.center(20))                 #        abd           
  12. print(s.center(20"*"))            #********abd*********  
  13. #--------------------------------------------------------------------  
  14. s.count(t, start, end)  #返回在s字符串中,start:end分片中,  
  15.                         #子串t出現的次數  
  16. s = "abcdabcdabcd" 
  17. s.count("bc")                       #3  
  18. s.count("bcda")                     #2  
  19. s.count("bcda"18)               #1  
  20. #--------------------------------------------------------------------  
  21. s.encode(encoding, err) #返回一個bytes對象用指定編碼格式來表示該字符串  
  22.                         #並根據可選的err處理錯誤  
  23. s = "中國" 
  24. print(s.encode(encoding='utf_8', errors='strict'))  
  25.                                     #b'\xe4\xb8\xad\xe5\x9b\xbd'   
  26. print(s.encode(encoding='GB2312', errors='strict'))  
  27.                                     #b'\xd6\xd0\xb9\xfa'  
  28. print(s.encode(errors='strict'))    #b'\xe4\xb8\xad\xe5\x9b\xbd'  
  29.                                     #默認的encoding是'utf_8'  
  30. #--------------------------------------------------------------------  
  31. s.endswith(x, start, end)   #如果在s或s[start:end]分片中從字符串x或  
  32.                             #元組x中的任意字符串結尾,則返回True,否則返回False  
  33. s = "中華人民共和國" 
  34. x = "國" 
  35. print(s.endswith(x))                #True  
  36. print(s.endswith(x, 25))          #False  
  37. x = ('一''國')  
  38. print(s.endswith(x))                #True  
  39. #--------------------------------------------------------------------  
  40. s.expandtabs(size)      #返回s的一個副本,其中製表符用8(默認)或size個空格替換  
  41.                         #這個替換不是直接在tab的位置上插入size個空格,而是與前文相關聯計算空格數  
  42. s = "abc\tdef\tghi" 
  43. print(s.expandtabs(4))              #abc def ghi  
  44. print(s.expandtabs(8))              #abc     def     ghi  
  45. print(s.expandtabs())               #abc     def     ghi  
  46. #--------------------------------------------------------------------  
  47. s.find(t, start, end)   #返回t在s或s[start:end]之中的最左位置,如果沒有找到返回-1  
  48.                         #使用s.rfind()可以返回相應的最右位置  
  49. s = "this is a test text" 
  50. print(s.find('is'))                 #2  
  51. print(s.rfind('is'))                #5  
  52. #--------------------------------------------------------------------  
  53. s.format(...)           #格式化字符串,這個在後面詳細解釋  
  54. #--------------------------------------------------------------------  
  55. s.index(t, start, end)  #返回t在s或s[start:end]之中的最左位置,如果沒有找到返回ValueError  
  56.                         #使用s.rindex()可以從最右邊開始搜索  
  57.                         #用法同s.find()                                
  58. #--------------------------------------------------------------------  
  59. s.isalnum()             #如果s非空,並且其中每個字符都是字母數字的就返回True  
  60. s = "abd123" 
  61. print(s.isalnum())                  #True  
  62. s += "_" 
  63. print(s.isalnum())                  #False  
  64. #--------------------------------------------------------------------  
  65. s.isalpha()             #如果s非空,並且其中每個字符都是字母的就返回True  
  66. s = "abd" 
  67. print(s.isalnum())                  #True  
  68. s += "123" 
  69. print(s.isalnum())                  #False  
  70. #--------------------------------------------------------------------  
  71. s.isdecimal()           #如果s非空,並且每個字符都是Unicode的基數爲10的數字就返回True  
  72. s = "1234" 
  73. print(s.isdecimal())                #True  
  74. s = "0x1304" 
  75. print(s.isdecimal())                #False  
  76. #--------------------------------------------------------------------  
  77. s.isdigit()             #如果非空,並且每個字符都是ASCII數字,則返回True  
  78. s = "1234" 
  79. print(s.isdigit())                  #True  
  80. s += "a" 
  81. print(s.isdigit())                  #False  
  82. #--------------------------------------------------------------------  
  83. s.isidentifier()        #如果s非空,並且是一個有效的標識符,則返回True  
  84. s = "abc" 
  85. print(s.isidentifier())             #True  
  86. s = "abc#%^#" 
  87. print(s.isidentifier())             #False  
  88. #--------------------------------------------------------------------  
  89. s.islower()             #如果s有至少一個小寫字符,並且所有小寫字符都是小寫就返回True  
  90. s = "abc" 
  91. print(s.islower())                  #True  
  92. s = "Abc" 
  93. print(s.islower())                  #False  
  94. s = "123" 
  95. print(s.islower())                  #False  
  96. #--------------------------------------------------------------------  
  97. s.isnumeric()           #同s.isdigit(),字符爲Unicode字符  
  98. #--------------------------------------------------------------------  
  99. s.isprintable()         #如果s非空,並且每個字符都是可打印字符,  
  100.                         #包括空格但不包括換行,則返回True  
  101. s = "this is a text" 
  102. print(s.isprintable())              #True  
  103. s = "this is a text\n" 
  104. print(s.isprintable())              #False  
  105. #--------------------------------------------------------------------  
  106. s.isspace()             #如果s非空,並且所有字符都是空白,則返回True  
  107. s = "   " 
  108. print(s.isspace())                  #True  
  109. s = "  1 " 
  110. print(s.isspace())                  #False  
  111. #--------------------------------------------------------------------  
  112. s.istitle()             #如果s是非空的且首字母大寫的字符串就返回True  
  113. s = "This is a test" 
  114. print(s.istitle())                  #False  
  115. s = "This Is A Test" 
  116. print(s.istitle())                  #True  
  117. #--------------------------------------------------------------------  
  118. s.isupper()             #如果s有至少一個可大寫字符且所有可大寫字符均爲大寫則返回True  
  119.                         #可參考s.islower()  
  120. #--------------------------------------------------------------------  
  121. s.join(seq)             #返回序列中所有項連接起來的結果,  
  122.                         #並以s(可以爲空)在每兩項之間分隔  
  123. s = "*" 
  124. seqs = ("this""is""a""test")  
  125. print(s.join(seqs))                 #this*is*a*test  
  126. print(" ".join(seqs))               #this is a test  
  127. print("".join(seqs))                #thisisatest  
  128. print(" ".join(["this""is""a""test"]))  
  129.                                     #this is a test  
  130. #--------------------------------------------------------------------  
  131. s.ljust(width, char)    #返回一個長度爲width的字符串,並以char來添充s左側  
  132.                         #可參考s.center(),s.rjust()爲右添充  
  133. #--------------------------------------------------------------------  
  134. s.lower()               #將s中的字符變爲小寫  
  135. s = "ABC123" 
  136. print(s.lower())                    #abc123  
  137. #--------------------------------------------------------------------  
  138. s.maketrans()           #與s.translate()對應,可以產生一個轉換表  
  139. a = "abcde" 
  140. b = "Hello" 
  141. x = a.maketrans(a, b)  
  142. print(a.translate(x))               #Hello  
  143.                         #貌似可以進行替換,或是小小的加密也不錯  
  144. #--------------------------------------------------------------------  
  145. s.partition(t)          #返回三個字符串的無級,分別是:  
  146.                         #s中在t子串之前的部分  
  147.                         #t  
  148.                         #s中在t子串之後的部分  
  149.                         #如果t不在s中,則返回s與兩個空字符串  
  150.                         #使用s.lpartition(t)可以在s最右邊分區  
  151. s = "My country is China" 
  152. t = "country" 
  153. print(s.partition(t))               #('My ', 'country', ' is China')  
  154. t = "ABCD" 
  155. print(s.partition(t))               #('My country is China', '', '')  
  156. t = "is" 
  157. print(s.rpartition(t))              #('My country ', 'is', ' China')  
  158. #--------------------------------------------------------------------  
  159. s.replace(t, u, n)      #返回字符串s的一個副本,其中每個或n個t用u替換  
  160. s = "this is a text" 
  161. print(s.replace("is""Is"))        #thIs Is a text  
  162. print(s.replace("is""Is"1))     #thIs is a text  
  163. #--------------------------------------------------------------------  
  164. s.split(t, n)           #返回一個字符串列表,在t處最多分割n次  
  165.                         #如果n沒指定,就儘可能分割多次  
  166.                         #如果t沒指定,就以空白處分割  
  167.                         #s.rsplit(t, n)是從右側開始分割,只有指定n,  
  168.                         #且n小於可分割的最大次數時纔有效  
  169. s = "this is a test text" 
  170. print(s.split("s"))                 #['thi', ' i', ' a te', 't text']  
  171. print(s.split('s'2))              #['thi', ' i', ' a test text']  
  172. print(s.rsplit('s'2))             #['this i', ' a te', 't text']  
  173. #--------------------------------------------------------------------  
  174. s.splitlines(f)         #返回的行終結符處分割產生的行列表  
  175.                         #並剝離行終結符(除非f爲True)  
  176.  
  177. print(s.splitlines())               #['this', 'is', 'a', 'test', 'text']  
  178. print(s.splitlines(True))           #['this\n', 'is\n', 'a\n', 'test\n', 'text']  
  179. #--------------------------------------------------------------------  
  180. s.startswith(x, start, end)  
  181.                         #如果字符串s或s[start:end]是以字符串x,  
  182.                         #或元組中任一項開始,則返回True,否則返回False  
  183.                         #可參考s.endswith()  
  184. #--------------------------------------------------------------------  
  185. s.strip(chars)          #將字符串開始和結尾處的chars中的字符移除  
  186.                         #chars默認爲空格  
  187.                         #s.lstrip(chars)爲去除字符串開始處的chars  
  188.                         #s.rstrip(chars)爲去除字符串結尾處的chars  
  189. print(" my name is Xiaoming. ".strip())  
  190.                                     #my name is Xiaoming.   
  191. print(" my name is Xiaoming. ".lstrip())  
  192.                                     #my name is Xiaoming.  
  193. print(" my name is Xiaoming. ".rstrip())  
  194.                                     # my name is Xiaoming.  
  195. #--------------------------------------------------------------------  
  196. s.swepcase()            #將字符串中大寫轉換成小寫,小寫轉換成大寫  
  197. s = "This Is A Test Text" 
  198. print(s.swapcase())                 #tHIS iS a tEST tEXT  
  199. #--------------------------------------------------------------------  
  200. s.title()               #將每個單詞的首字母轉成大寫,其它字母轉成小寫  
  201. s ="tHIS iS a tEST tEXT" 
  202. print(s.title())                    #This Is A Test Text  
  203. #--------------------------------------------------------------------  
  204. s.upper()               #將字符全部轉換成大寫,可參考s.lower()  
  205. #--------------------------------------------------------------------  
  206. s.zfill(width)          #返回s的副本,如果s長度小於width則在開始處添加0使之長度爲width  
  207. s = "test" 
  208. print(s.zfill(15))                  #00000000000test  
  209. #-------------------------------------------------------------------- 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章