Python基础知识(七)--字符串详解

来源:互联网 发布:渣优化 编辑:程序博客网 时间:2024/06/16 12:57
  1. #字符串是一个序列,因此也是有大小的对象。
  2. #可以使用字符串为参数调用len()函数
  3. #在字符串操作中,+运算符被重载用于字符串连接
  4. #如果需要连接大量字符串,str.join()是一个更好的方法
  5. #该方法以一个序列做为参数(字符串列表或字符串元组)
  6. #并将其连接在一起存放在一个单独的字符串中,
  7. #并将调用该方法的字符串做为分隔符添加在每两项之间
  8. treatises = ["Arithmetica", "conics", "Elements"]
  9. print(" ". join(treatises)) #Arithmetica conics Elements
  10. print("-<>-".join(treatises)) #Arithmetica-<>-conics-<>-Elements
  11. print("".join(treatises)) #ArithmeticaconicsElements
  12. #str.join()方法可以与内置的reversed()函数一起使用,以实现对字符串的反转
  13. #"".join(reversed(s)),当然可以通过步距更精确的获取同样的结果s[::-1]
  14. s = "This is a test"
  15. print("".join(reversed(s))) #tset a si sihT
  16. print(s[::-1]) #tset a si sihT
  17. # * 操作符提供了字符串复制功能
  18. s = "=" * 5
  19. print(s) #=====
  20. s *= 2
  21. print(s) #==========
  22. #在用于字符串时,成员操作符in左边的字符串如果是右边字符串的一部分或是相等就返回True
  23. s = "This is a test"
  24. t = "This"
  25. print(t in s) #True
  26. #如果需要在某个字符串中打到另一个字符串的位置,有两种方法:
  27. #1.使用str.index()方法,该方法返回子字符串的索引位置,或在失败时返回一个ValueError
  28. #2.使用str.find()方法,该方法返回子字符串的索引位置,或在失败时返回-1
  29. #如果搜索多个索引位置,str.index()通常会产生更干净的代码
  30. def extract_from_tag(tag, line):
  31. opener = "<" + tag + ">"
  32. closer = "</" + tag + ">"
  33. try:
  34. i = line.index(opener)
  35. start = i + len(opener)
  36. j = line.index(closer, start)
  37. return line[start:j]
  38. except ValueError:
  39. return None
  40. def extract_from_tag(tag, line):
  41. opener = "<" + tag + ">"
  42. closer = "</" + tag + ">"
  43. i = line.find(opener)
  44. if i != -1:
  45. start = i + len(opener)
  46. j = line.find(closer, start)
  47. if j != -1:
  48. return line[start:j]
  49. return None
  50. #可以使用单独的字符串做为str.endswith()或str.startswith()的参数
  51. #也可以使用字符串元组做参数
  52. if filename.lower().endswith((".jpg", ".jpeg")):
  53. print(filename, "is a JPEG image")
  54. #如果参数字符串至少有一个字符,并且字符串中的每个字符都符合标准
  55. #is*()(isalpha()、isspace())方法就返回True
  56. #由于is*()调用的是字符Unicode分类,所以不能因为isdigit()返回True
  57. #就判断可以转换成整数
  58. print("\N{Circled digit two}") #②
  59. print("\N{Circled digit two}".isdigit()) #True
  60. print(int("\N{Circled digit two}")) #invalid literal for int() with base 10: '②'
  61. #可以使用str.lstrip()、str.rstrip()、str.strip()来剥离空格
  62. s = "\t no parking"
  63. print(s.lstrip()) #no parking
  64. print(s.rstrip()) # no parking
  65. print(s.strip()) #no parking
  66. print("[<unbracketed>]".strip("[]{}<>()")) #unbracketed
  67. #str.replace()方法用来在字符串内进行替换,并返回该副本
  68. #它以两个字符串做为参数
  69. #第一个字符串所有出现均被替换成第二个字符串
  70. #如果第二个字符串为空的话,实际效果是删除所有第一个字符串相同的内容
  71. s = "This*is*a*test"
  72. print(s.replace("*", " ")) #This is a test
  73. print(s.replace("*", "")) #Thisisatest
  74. #通过str.split()方法可以分割字符串
  75. record = "Leo Tolstoy*1828-8-28*1910-11-20"
  76. fields = record.split("*")
  77. print(fields) #['Leo Tolstoy', '1828-8-28', '1910-11-20']
  78. born = fields[1].split("-")
  79. died = fields[2].split("-")
  80. print("lived about", int(died[0]) - int(born[0]), years)
  81. #lived about 82 years
  82. #也可以从fields列表获取年份
  83. year_born = int(fields[1].split("-")[0])
  84. #str.maketrans() and str.translate()
  85. table = "".maketrans("\N{bengali digit zero}"
  86. "\N{bengali digit one}\N{bengali digit two}"
  87. "\N{bengali digit three}\N{bengali digit four}"
  88. "\N{bengali digit five}\N{bengali digit six}"
  89. "\N{bengali digit seven}\N{bengali digit eight}"
  90. "\N{bengali digit nine}", "0123456789")
  91. print("20749".translate(table)) #20749
  92. print("\N{bengali digit two}07\N{bengali digit four}"
  93. "\N{bengali digit nine}".translate(table))
  94. #20749
  95. #Python还提供了一些其它的库模块提供了字符串相关的功能
  96. #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. #decimal.Decimal有两种方式输出
  3. >>> import decimal
  4. >>> decimal.Decimal("3.4084")
  5. Decimal('3.4084')
  6. >>> print(decimal.Decimal("3.4084"))
  7. 3.4084
  8. #第一种方式是其表象形式,提供一个字符串
  9. #该字符串在被Python解释时,重建其表示的对象
  10. #并不是所有对象都提供这种便于重建的表象形式
  11. #如果提供,其形式为包含在尖括号中的字符串
  12. >>> import sys
  13. >>> sys
  14. <module 'sys' (built-in)>
  15. #第二种是以字符串形式对decimal.Decimal进行展示的
  16. #如果某种对象没有字符串表示形式,但又需要使用字符串进行表示
  17. #那么Python将使用表象形式
  18. #Python内置的数据类型都知道str.format()
  19. #在作为参数传递给这一方法时,将返回一个适当的字符串来展示自己
  20. #为自定义类型添加str.format()方法的支持是很直接的
  21. #重写数据类型的通常行为并强制其提供字符串形式或表象形式也是可能的
  22. #这是通过向指定字段中添加conversion指定符来实现的
  23. #目前有三个这样的指定符
  24. # s 用于强制使用字符串形式
  25. # r 强制使用表象形式
  26. # a 强制使用表象形式,但仅限于ASCII字符
  27. print("{0} {0!s} {0!r} {0!a}".format(decimal.Decimal("93.4")))
  28. #93.4 93.4 Decimal('93.4') Decimal('93.4')

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