【问题标题】:Python white space symbol removing \sPython空格符号删除\ s
【发布时间】:2014-04-11 12:32:33
【问题描述】:

例如,我有这个地址 \sgoogle.com 并且我使用

line.strip(' \s') # it displays google.com as it must be

但是当我在 \sgoogle\s.com 上尝试它时,它工作得不好(结果是 googles.com)。有谁知道出了什么问题以及如何解决?

【问题讨论】:

  • strip 仅删除前导/尾随字符
  • 使用一些正则表达式库函数,如Regex.Replace(pattern,input)。我们在C#中使用这种函数

标签: python regex trim


【解决方案1】:

strip() 只删除字符串开头和结尾的这些字符,而不是字符串中间的字符。如果要在字符串中的任何位置删除它,请使用replace

'\sgoogle\s.com'.replace('\s', '');

【讨论】:

    【解决方案2】:

    我想我可能会包含一个替代方案(仅限 Python 2):

    >>> s = '\sgoogle\s.com'
    >>> s.translate(None, '\s')
    'google.com'
    

    在 Python 3 中是:

    >>> s.translate(s.maketrans('', '', '\s'))
    'google.com'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多