【问题标题】:Removing Spaces from Strings in Python 3.x在 Python 3.x 中从字符串中删除空格
【发布时间】:2010-11-03 02:23:38
【问题描述】:

我需要转换字符串:

"There are 6 spaces in this string."

到:

"Thereare6spacesinthisstring."

【问题讨论】:

    标签: python string python-3.x


    【解决方案1】:

    您可以使用replace

    string = "There are 6 spaces in this string"
    string = string.replace(' ', '')
    

    【讨论】:

    • LJ3:通过单击答案左侧的复选标记来接受答案以及对您认为有用的答案进行投票也被认为是一件好事
    【解决方案2】:
    new = "There are 6 spaces in this old_string.".replace(' ', '')
    

    如果你想去掉所有空格,包括制表符:

    new = ''.join( old_string.split() )
    

    【讨论】:

    • re.subn 处理空格不是更好吗?还是两者等价?
    • 感谢尝试了上面的替换版本,但没有成功,加入拆分解决方案很优雅,而且效果很好......顺便说一句 Python 3.2.3
    【解决方案3】:

    你可以使用 replace() :

    print(string.replace(" ", ""))
    

    您还可以使用 rstrip、lstrip 或 strip 删除结尾/开头(或两者!)的白色字符。

    【讨论】:

      猜你喜欢
      • 2015-04-21
      • 2017-11-20
      • 2011-09-21
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多