1. #字符串是一个序列,因此也是有大小的对象。  
  2. #可以使用字符串为参数调用len()函数  
  3.  
  4. #在字符串操作中,+运算符被重载用于字符串连接  
  5. #如果需要连接大量字符串,str.join()是一个更好的方法  
  6. #该方法以一个序列做为参数(字符串列表或字符串元组)  
  7. #并将其连接在一起存放在一个单独的字符串中,  
  8. #并将调用该方法的字符串做为分隔符添加在每两项之间  
  9. treatises = ["Arithmetica""conics""Elements"]  
  10. print(" ". join(treatises))                 #Arithmetica conics Elements  
  11. print("-<>-".join(treatises))               #Arithmetica-<>-conics-<>-Elements  
  12. print("".join(treatises))                   #ArithmeticaconicsElements  
  13. #str.join()方法可以与内置的reversed()函数一起使用,以实现对字符串的反转  
  14. #"".join(reversed(s)),当然可以通过步距更精确的获取同样的结果s[::-1]  
  15. s = "This is a test" 
  16. print("".join(reversed(s)))                 #tset a si sihT  
  17. print(s[::-1])                              #tset a si sihT  
  18. # * 操作符提供了字符串复制功能  
  19. s = "=" * 5 
  20. print(s)                                    #=====  
  21. s *= 2 
  22. print(s)                                    #==========  
  23. #在用于字符串时,成员操作符in左边的字符串如果是右边字符串的一部分或是相等就返回True  
  24. s = "This is a test" 
  25. t = "This" 
  26. print(t in s)                               #True  
  27. #如果需要在某个字符串中打到另一个字符串的位置,有两种方法:  
  28. #1.使用str.index()方法,该方法返回子字符串的索引位置,或在失败时返回一个ValueError  
  29. #2.使用str.find()方法,该方法返回子字符串的索引位置,或在失败时返回-1  
  30. #如果搜索多个索引位置,str.index()通常会产生更干净的代码  
  31.  
  32. def extract_from_tag(tag, line):  
  33.     opener = "<" + tag + ">" 
  34.     closer = "</" + tag + ">" 
  35.     try:  
  36.         i = line.index(opener)  
  37.         start = i + len(opener)  
  38.         j = line.index(closer, start)  
  39.         return line[start:j]  
  40.     except ValueError:  
  41.         return None 
  42.       
  43.  
  44. def extract_from_tag(tag, line):  
  45.     opener = "<" + tag + ">" 
  46.     closer = "</" + tag + ">" 
  47.     i = line.find(opener)  
  48.     if i != -1:  
  49.         start = i + len(opener)  
  50.         j = line.find(closer, start)  
  51.         if j != -1:  
  52.             return line[start:j]  
  53.     return None 
  54.  
  55. #可以使用单独的字符串做为str.endswith()或str.startswith()的参数  
  56. #也可以使用字符串元组做参数  
  57. if filename.lower().endswith((".jpg"".jpeg")):  
  58.     print(filename, "is a JPEG p_w_picpath")  
  59. #如果参数字符串至少有一个字符,并且字符串中的每个字符都符合标准  
  60. #is*()(isalpha()、isspace())方法就返回True  
  61. #由于is*()调用的是字符Unicode分类,所以不能因为isdigit()返回True  
  62. #就判断可以转换成整数  
  63. print("\N{Circled digit two}")                  #②  
  64. print("\N{Circled digit two}".isdigit())        #True  
  65. print(int("\N{Circled digit two}"))             #invalid literal for int() with base 10: '②'  
  66. #可以使用str.lstrip()、str.rstrip()、str.strip()来剥离空格  
  67. s = "\t no parking" 
  68. print(s.lstrip())                               #no parking  
  69. print(s.rstrip())                               #     no parking  
  70. print(s.strip())                                #no parking  
  71. print("[<unbracketed>]".strip("[]{}<>()"))      #unbracketed  
  72. #str.replace()方法用来在字符串内进行替换,并返回该副本  
  73. #它以两个字符串做为参数  
  74. #第一个字符串所有出现均被替换成第二个字符串  
  75. #如果第二个字符串为空的话,实际效果是删除所有第一个字符串相同的内容  
  76. s = "This*is*a*test" 
  77. print(s.replace("*"" "))                      #This is a test  
  78. print(s.replace("*", ""))                       #Thisisatest  
  79. #通过str.split()方法可以分割字符串  
  80. record = "Leo Tolstoy*1828-8-28*1910-11-20" 
  81. fields = record.split("*")  
  82. print(fields)                                   #['Leo Tolstoy', '1828-8-28', '1910-11-20']  
  83. born = fields[1].split("-")  
  84. died = fields[2].split("-")  
  85. print("lived about", int(died[0]) - int(born[0]), years)  
  86.                                                 #lived about 82 years  
  87. #也可以从fields列表获取年份  
  88. year_born = int(fields[1].split("-")[0])  
  89.  
  90. #str.maketrans() and str.translate()  
  91. table = "".maketrans("\N{bengali digit zero}"  
  92.              "\N{bengali digit one}\N{bengali digit two}" 
  93.              "\N{bengali digit three}\N{bengali digit four}" 
  94.              "\N{bengali digit five}\N{bengali digit six}" 
  95.              "\N{bengali digit seven}\N{bengali digit eight}" 
  96.              "\N{bengali digit nine}""0123456789")  
  97. print("20749".translate(table))                 #20749  
  98. print("\N{bengali digit two}07\N{bengali digit four}" 
  99.       "\N{bengali digit nine}".translate(table))  
  100.                                                 #20749  
  101. #Python还提供了一些其它的库模块提供了字符串相关的功能  
  102. #unicodedata/difflib/io/textwrap/string/re 
 
  
  1. #使用str.format()进行字符串格式化  
  2. print("The novel '{0}' was published in {1}".format("Hard Times"1854))  
  3.                                                 #The novel 'Hard Times' was published in 1854  
  4. #每个替换字段都由花括号中的字段名标识的,如果字段名是简单的整数  
  5. #就将被作为传递给str.format()方法的一个参数的索引位置  
  6. #名为0的字段被第一个参数代替,名为1的被第二个参数代替  
  7. #如果需要格式化的字符串包含花括号,就要将它复写  
  8. print("{`0`}{1};-}}".format("I'm in braces""I'm not"))  
  9.                                                 #{I'm in braces}I'm not;-}  
  10. #如果我们试图连接数字和字符串,则会产生TypeError异常  
  11. #但用str.format()方法则可以很容易做到这一点  
  12. print("{0}{1}".format("The amount due is $"200))  
  13.                                                 #The amount due is $200  
  14. x = "three" 
  15. s = "{0}{1}{2}" 
  16. s = s.format("The", x, "tops")  
  17. print(s)                                        #Thethreetops  
  18. #字段名还可以使用关键字参数  
  19. print("{who} turned {age} this year".format(who = "She", age = 88))  
  20.                                                 #She turned 88 this year  
  21. print("The {who} was {0} last week".format(12, who = "boy"))  
  22.                                                 #The boy was 12 last week  
  23. #字段名可以引用集合数据类型如列表,  
  24. #这种情况下可以包含一个索引(不是一个分片)来标志数据项  
  25. stock = ["paper""envelopes""notepads""pens""paper clips"]  
  26. print("We have {0[1]} and {0[2]} in stock".format(stock))  
  27.                                                 #We have envelopes and notepads in stock  
  28. #字典对象也可以用于str.format()  
  29. d = dict(animal = "elephant", weight = 12000)  
  30. print("The {0[animal]} weighs {0[weight]}kg".format(d))  
  31.                                                 #The elephant weighs 12000kg  
  32. #也可以存取命名的属性  
  33. import math, sys  
  34. print("math.pi=={0.pi} sys.maxunicode=={1.maxunicode}".format(math, sys))  
  35.                                                 #math.pi==3.141592653589793 sys.maxunicode==65535  
  36. #从Python3.1开始,忽略字段名成为可能,  
  37. #这种情况下Python会自动处理(使用从0开始的数值)  
  38. print("{} {} {}".format("Python""can""count"))  
  39.                                                 #Python can count  
  40. #当前还在作用范围的局部变量可以通过内置的locals()函数来访问  
  41. #该函数会返回一个字典,字典的键是局部变量名,  
  42. #值则是对变量值的引用  
  43. #映射拆分操作符为**,用来产生一个适合传递给函数的键-值列表  
  44. element = "Sliver" 
  45. number = 47 
  46. print("Element {number} is {element}".format(**locals()))  
  47.                                                 #Element 47 is Sliver  
  48. #将字典拆分提供给str.format()时,允许使用字典的键作为字段名  
  49. #这使得字符串格式更容易理解,更易维护  
  50. #因为不需要依赖于参数的顺序  
  51. #然而,当需要将不止一个参数传递给str.format()  
  52. #那么只有最后一个参数才可以使用映射拆分 
 
  
  1. #转换  
  2.  
  3. #decimal.Decimal有两种方式输出  
  4. >>> import decimal  
  5. >>> decimal.Decimal("3.4084")  
  6. Decimal('3.4084')  
  7. >>> print(decimal.Decimal("3.4084"))  
  8. 3.4084 
  9. #第一种方式是其表象形式,提供一个字符串  
  10. #该字符串在被Python解释时,重建其表示的对象  
  11. #并不是所有对象都提供这种便于重建的表象形式  
  12. #如果提供,其形式为包含在尖括号中的字符串  
  13. >>> import sys  
  14. >>> sys  
  15. <module 'sys' (built-in)>  
  16. #第二种是以字符串形式对decimal.Decimal进行展示的  
  17. #如果某种对象没有字符串表示形式,但又需要使用字符串进行表示  
  18. #那么Python将使用表象形式  
  19. #Python内置的数据类型都知道str.format()  
  20. #在作为参数传递给这一方法时,将返回一个适当的字符串来展示自己  
  21. #为自定义类型添加str.format()方法的支持是很直接的  
  22. #重写数据类型的通常行为并强制其提供字符串形式或表象形式也是可能的  
  23. #这是通过向指定字段中添加conversion指定符来实现的  
  24. #目前有三个这样的指定符  
  25. # s 用于强制使用字符串形式  
  26. # r 强制使用表象形式  
  27. # a 强制使用表象形式,但仅限于ASCII字符  
  28. print("{0} {0!s} {0!r} {0!a}".format(decimal.Decimal("93.4")))  
  29.                                         #93.4 93.4 Decimal('93.4') Decimal('93.4') 

 

 
  
  1. #格式规约  
  2. #整数、浮点数以及字符串的默认格式通常都足以满足要求,  
  3. #但是如果需要实施更精确的控制,我们就可以通过格式规约很容易地实现。  
  4.  
  5.  
  6. #对于字符串而言,我们可以控制的包括填充字符、  
  7. #字段内对齐方式以及字段宽度的最小值与最大值。  
  8. #字符串格式规约是使用冒号(:)引入的,  
  9. #其后跟随可靠的字符对--一个填充字符与一个对齐字符(<用于左对齐,  
  10. #^用于中间对齐,>用于右对齐),之后跟随一个整数值。  
  11. #要注意的是,如果指定了一个填充字符,就必须同时指定对齐字符。  
  12.  
  13. >>> s = "The sword of truth" 
  14. >>> "{0}".format(s)  
  15. 'The sword of truth' 
  16. >>> "{0:25}".format(s)  
  17. 'The sword of truth       ' 
  18. >>> "{0}".format(s)                 #默认格式  
  19. 'The sword of truth' 
  20. >>> "{0:25}".format(s)              #最小宽度25  
  21. 'The sword of truth       ' 
  22. >>> "{0:>25}".format(s)             #最小宽度25,右对齐  
  23. '       The sword of truth' 
  24. >>> "{0:^25}".format(s)             #最小宽度25,居中对齐  
  25. '   The sword of truth    ' 
  26. >>> "{0:-^25}".format(s)            #最小宽度25,居中对齐,添充-  
  27. '---The sword of truth----' 
  28. >>> "{0:.<25}".format(s)            #最小宽度25,左对齐,添充.  
  29. 'The sword of truth.......' 
  30. >>> "{0:.10}".format(s)             #最大宽度10  
  31. 'The sword ' 
  32. #在格式化规约内部包括替换字段是可以的,从而有可计算的格式也是可能的。  
  33. >>> maxwidth = 12 
  34. >>> "{0}".format(s[:maxwidth])  
  35. 'The sword of' 
  36. >>> "{0:.{1}}".format(s, maxwidth)  
  37. 'The sword of' 
  38. #第一种方法使用了标准的字符串分片  
  39. #第二种方法使用内部替换字段  
  40.  
  41. #对于整数,通过格式规约,可以控制填充字符、字段内对齐、符号、最小字段宽度、基数等  
  42. #格式规约以冒号开始,其后可以跟随一个可靠的字符对--一个填充字符与  
  43. #一个对齐字符(<用于左对齐,^用于居中对齐,>用于右对齐,=用于在符号与数字之间进行填充),  
  44. #之后跟随的是可选的符号字符:+表示必须输出符号,-表示只输出负数符号,  
  45. #空格表示为正数输出空格,为负数输出符号-。  
  46. #再之后跟随的是可选的最小宽度整数值--其前可以使用字符#引导,  
  47. #以便获取某种基数进制为前缀的输出(对二进制、八进制、十六进制数值),  
  48. #也可以以0引导,以便在对齐时使用0进行填充。  
  49. #如果希望输出其他进制数据,而非十进制数,就必须添加一个类型字符--  
  50. # b用于表示二进制,o用于表示八进制,x用于表示小写十六进制,X用于表示大写十六进制,  
  51. #为了完整性,也可以使用d表示十进制整数。  
  52. #此外还有两个其他类型字符:c,表示输出对应的Unicode字符;n,表示以场所第三的方式输出数字。  
  53. #填充实例  
  54. >>> "{0:0=12}".format(8749203)          #最小宽度12,用0填充,填充位置在符号和数字之间  
  55. '000008749203' 
  56. >>> "{0:0=12}".format(-8749203)         #最小宽度12,用0填充,填充位置在符号和数字之间  
  57. '-00008749203' 
  58. >>> "{0:012}".format(8749203)           #最小宽度12,用0填充  
  59. '000008749203' 
  60. >>> "{0:012}".format(-8749203)          #最小宽度12,用0填充  
  61. '-00008749203' 
  62. #填充对齐  
  63. >>> "{0:*<15}".format(18340427)         #最小宽度15,左对齐,用*填充  
  64. '18340427*******' 
  65. >>> "{0:*>15}".format(18340427)         #最小宽度15,右对齐,用*填充  
  66. '*******18340427' 
  67. >>> "{0:*^15}".format(18340427)         #最小宽度15,居中对齐,用*填充  
  68. '***18340427****' 
  69. >>> "{0:*^15}".format(-18340427)        #最小宽度15,居中对齐,用*填充  
  70. '***-18340427***' 
  71. #符号字符  
  72. >>> "[{0: }] [{1: }]".format(539802, -539802)       #前缀符号或空格  
  73. '[ 539802] [-539802]' 
  74. >>> "[{0:+}] [{1:+}]".format(539802, -539802)       #必须输出符号  
  75. '[+539802] [-539802]' 
  76. >>> "[{0:-}] [{1:-}]".format(539802, -539802)       #只有负数输出符号  
  77. '[539802] [-539802]' 
  78. >>> "[{0:*^-15}] [{1:*^-15}]".format(539802, -539802)   #只有负数输出符号,居中,宽度15,以*填充  
  79. '[****539802*****] [****-539802****]' 
  80. #类型字符  
  81. "{0:b} {0:o} {0:x} {0:X}".format(14613198)          #各种进制表示  
  82. '110111101111101011001110 67575316 deface DEFACE' 
  83. >>> "{0:#b} {0:#o} {0:#x} {0:#X}".format(14613198)  
  84. '0b110111101111101011001110 0o67575316 0xdeface 0XDEFACE' 
  85. #为整数指定最大字段宽度是不可能的,这是因为,  
  86. #这样做要求数字是可裁剪的,并可能会使整数没有意义。  
  87. #如果使用Python3.1,并在格式规范中使用一个逗号,则整数将使用逗号进行分组:  
  88. >>> "{0:,} {0:*>13,}".format(int(2.39432185e6))  
  89. '2,394,321 ****2,394,321' 
  90. #最后一个可用于整数(也可用于浮点数)的格式化字符是n。  
  91. #在给定的字符是整数时,其作用与 d 相同;在给定的字符是浮点数时,其作用于 g 相同。  
  92. # n 的特殊之处在于,充分考虑了当前的场所,并在其产生的输出信息中使用场所特定的十进制字符与分组字符。  
  93. #默认的场所称为C场所,对这种C场所,十进制字符是一个句点,分组字符是一个空字符串。  
  94. #在程序的起始处添加下面两行,并将其作为最先执行的语句,通过这种方式,可以充分考虑不同用户的场所:  
  95. import locale  
  96. locale.setlocale(locale.LC_ALL, "")         #"Chinese_People's Republic of China.936"  
  97. x, y = (12345678901234.56)  
  98. c = "{0:n}  {1:n}".format(x, y)  
  99. print(c)                                    #1,234,567,890  1,234.56  
  100. locale.setlocale(locale.LC_ALL, "C")        #'C'  
  101. c = "{0:n}  {1:n}".format(x, y)  
  102. print(c)                                    #1234567890  1234.56  
  103. #虽然n对于整数非常有用,但是对于浮点数的用途有限,因为随着浮点数的增大,  
  104. #就会使用指数形式对其进行输出。  
  105. #对于浮点数,通过格式规约,可以控制填充字符、字段对齐、符号、最小字段宽度、  
  106. #十进制小数点后的数字个数,以及是以标准形式、指数形式还是以百分数的形式输出数字。  
  107. #用于浮点的格式规约与用于的格式规约是一样的,只是在结尾处有两个差别。  
  108. #在可靠的最小宽度后面,通过写一个句点并在其后跟随一个整数,  
  109. #我们可以指定在小数点后跟随的数字个数。  
  110. #我们也可以在结尾处添加一个类型字符: e 表示使用小写字母 e 的指数形式,  
  111. # E 表示使用大写字母E的指数形式,f 表示标准的浮点形式,  
  112. # g 表示“通常”格式--这与f的作用是相同的,除非数字特别大(在这种情况下与 e的作用相同--  
  113. #以及几乎与 g 赞同的 G,但总是使用f或E)。  
  114. #另一个可以使用的是%--这会导致数字扩大100倍,  
  115. #产生的数字结果使用 f 并附加一个%字符的格式输出。  
  116. >>> import math  
  117. >>> amount = ( 10 ** 3) * math.pi  
  118. >>> print("[{0:12.2e}] [{0:12.2f}]".format(amount))         #最小宽度12,小数点后2位  
  119. [    3.14e+03] [     3141.59]  
  120. >>> print("[{0:*>12.2e}] [{0:*>12.2f}]".format(amount))  
  121. [****3.14e+03] [*****3141.59]  
  122. >>> print("[{0:*>+12.2e}] [{0:*>+12.2f}]".format(amount))  
  123. [***+3.14e+03] [****+3141.59]  
  124. #从Python3.1开始,decimal.Decimal数值能够被格式化为floats,  
  125. #也能对逗号(,)提供支持,以获得用逗号进行隔离的组。  
  126. #在下面这个例子中,由于在Python3.1中不再需要字段免,所以这里将其删除。  
  127. >>> import decimal  
  128. >>> "{:,.6f}".format(decimal.Decimal("1234567890.1234567890"))  
  129. '1,234,567,890.123457' 
  130. >>> "{:,.6}".format(decimal.Decimal("1234567890.1234567890"))  
  131. '1.23457E+9' 
  132. #从Python3.1开始支持对复数的格式化,  
  133. #这是通过将复数的实数部分与虚数部分分别作为单独的浮点数进行格式化来实现的:  
  134. >>> "{0.real:.3f}{0.imag:+.3f}j".format(4.75917+1.2042j)  
  135. '4.759+1.204j' 
  136. >>> "{0.real:.3f}{0.imag:+.3f}j".format(4.75917-1.2042j)  
  137. '4.759-1.204j'