Python之str内置函数

约定不等于承诺〃 2022-06-02 03:54 327阅读 0赞
  • str.capitalize()

字串首字母大写

  1. a_str = "hello World"
  2. print("%s capitalized is %s" % (a_str, a_str.capitalize()))
  • str.casefold()

与lower()类似,将字串转换为小写,可用于大小写不敏感字串匹配
与lower()不同的是:lower方法只对ASCII编码,对于其他语言(非汉语或英文)可以使用casefold()进行大小写转换。
‘ß’是德语字符,其小写为’ss’

  1. b_str = 'ß'
  2. print("%s casefolded is %s" % (b_str, b_str.casefold()))
  3. print("%s lower is %s" % (b_str, b_str.lower()))

-str.center(width[, fillchar])

返回指定宽度width,以当前字串居中的字串,左右不足部分以fillchar来填充, 如果width不大于原字串宽度,则返回原字串

  1. if len(c_str) % 2 == 0 :
  2. if len(c_str) + 1 == width:
  3. do padding one fillchar on the left
  4. else:
  5. if len(c_str) + 1 == width:
  6. do padding one fillchar on the right
  7. c_str = 'abc'
  8. print(c_str.center(4, '#'))
  9. print(c_str.center(5, '#'))
  10. c_str = 'icbc'
  11. print(c_str.center(5, '#'))
  12. print(c_str.center(6, '#'))
  • str.count(sub[, start[, end]])

返回子串出现频率

  1. sub1 = "a"
  2. sub2 = "ac"
  3. sub3 = "a"
  4. sub4 = "aa"
  5. d_str = "abcdndiacac"
  6. e_str = "aaaaa"
  7. print(d_str.count(sub1)) print(d_str.count(sub2)) print(e_str.count(sub3)) print(e_str.count(sub4))
  • ljust(width[, fillchar])

使用指定字符填充,使字符串左对齐

  1. c_str = "icbc"
  2. # output: icbc$$
  3. print(c_str.ljust(6, '$'))
  • rindex(sub[, start[, end]])

使用指定字符填充,使字符串右对齐

  1. c_str = "icbc"
  2. # output: $$icbc
  3. print(c_str.rjust(6, '$'))

-zfill(width)

字符串右对齐,前面填充0,如果width小于原有子串长度,则返回原有子串

  1. n_str = '98'
  2. print(n_str.zfill(5))
  3. n_str = '-98'
  4. print(n_str.zfill(5))
  5. n_str = '--98'
  6. print(n_str.zfill(5))
  7. n_str = '-98'
  8. print(n_str.zfill(2))
  9. # output:
  10. # 00098
  11. # -0098
  12. # -0-98
  13. # -98

https://docs.python.org/3/library/stdtypes.html?#str

发表评论

表情:
评论列表 (有 0 条评论,327人围观)

还没有评论,来说两句吧...

相关阅读