【问题标题】:Why does str.strip() automatically removes all the escape characters?为什么 str.strip() 会自动删除所有转义字符?
【发布时间】:2014-07-09 06:10:32
【问题描述】:

采样一个字符串:

a = '   \r\rwww someString www\r\r\n\n   '

并采样以下两个结果。

[In]: a.strip()
[Out]: 'www someString www'

[In]: a.strip('w ')
[Out]: '\r\rwww someString www\r\r\n\n'

Python 文档对 str.strip([chars]) 的评论是:

如果省略或无,chars 参数默认删除空格

为什么还要删除所有转义字符?

【问题讨论】:

标签: python string


【解决方案1】:

它正在做它应该做的事情:去除前导和尾随字符。

示例字符串:

a = '   \r\rwww someString www\r\r\n\n   '

这会去除前导和尾随空格:

[In]: a.strip()
[Out]: 'www someString www'

\r\n 是空白字符,因此它们会被剥离。


这会去除前导和尾随 w 或文字空格(字符 32);它不会去除 \r\n 字符,它们是空白字符:

[In]: a.strip('w ')
[Out]: '\r\rwww someString www\r\r\n\n'

因为它不会删除\r\n,所以www 被单独留下。


在这两种情况下,内部空间都没有被触及。

【讨论】:

  • 去除前导和尾随空格,您不需要任何参数; a.strip() 会做到的。但是.strip() 不会删除任何内部空格。要去除前导、尾随和内部空格,a = re.sub(r"\s", "", a) 会这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多