当前位置:  首页>> 技术小册>> Python合辑3-字符串用法深度总结

str.strip([chars])

使用 strip 方法从字符串的两侧删除尾随空格或字符。例如:

  1. string = " Apple Apple Apple no apple in the box apple apple "
  2. stripped_string = string.strip()
  3. print(stripped_string)
  4. left_stripped_string = (
  5. stripped_string
  6. .lstrip('Apple')
  7. .lstrip()
  8. .lstrip('Apple')
  9. .lstrip()
  10. .lstrip('Apple')
  11. .lstrip()
  12. )
  13. print(left_stripped_string)
  14. capitalized_string = left_stripped_string.capitalize()
  15. print(capitalized_string)
  16. right_stripped_string = (
  17. capitalized_string
  18. .rstrip('apple')
  19. .rstrip()
  20. .rstrip('apple')
  21. .rstrip()
  22. )
  23. print(right_stripped_string)

Output:

  1. Apple Apple Apple no apple in the box apple apple
  2. no apple in the box apple apple
  3. No apple in the box apple apple
  4. No apple in the box

在上面的代码片段中,使用了 lstrip 和 rstrip 方法,它们分别从字符串的左侧和右侧删除尾随空格或字符。还使用了 capitalize 方法,它将字符串转换为句子大小写


该分类下的相关小册推荐: