Python基础知识(六)--字符串

发布时间:2019-09-12 07:58:28编辑:auto阅读(1857)

     

    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. #-------------------------------------------------------------------- 

关键字