Python超详细的字符串用法大全( 二 )


以上三种方法的基本用法:
>>> s = 'abc'>>> s.ljust(20, '=')'abc================='>>> s.ljust(20)'abc '三种方法都可以设置默认填充值
2.使用内置的 format() 方法
>>> format(s, ">20")' abc'>>> format(s, "<20")'abc '>>> format(s, "^20")' abc '删除字符串中不需要的字符
实际案例:

  1. 过滤掉用户输入中前后多余的空白字符:“ nick2008@gmail.com ”
  2. 过滤掉某 windows 下编辑文本中的 “r” :“hello world rn”
  3. 去掉文本中的 unicode 组合符号(音调):nǐ hǎo mā
解决方案:
  • 使用 str.strip(), str.lstrip(), str.rstrip() 方法去掉字符串两端字符
  • 使用 str.replace() 或者正则中的 re.sub()
  • 使用字符串中 str.translate() 方法,可以同时删除多个不同的字符

【Python超详细的字符串用法大全】


推荐阅读