【问题标题】:How to remove space(including tabs) in python 3?如何在 python 3 中删除空格(包括制表符)?
【发布时间】:2020-02-23 02:02:58
【问题描述】:

我尝试使用以下代码,但它不起作用

def output_without_whitespace(phrase):
    phrase = phrase.replace(' ','')
    new_phrase = phrase.replace("\t","")
    return new_phrase

对于以下短语:“狐狸\tjumped over the log。” 输出将是:“Thefox\tjumpedoverthelog。”

如何摆脱标签?

【问题讨论】:

  • 您的功能正常工作。似乎是什么问题?

标签: python-3.x string replace tabs


【解决方案1】:

您的功能应该可以正常工作,这是完成工作的好方法。我们还有其他方法可以消除空白。这是我最喜欢的一个:

import string
s = '  Hello  World! I   am  Luis !\t\n\r\tHi There  '
s.translate({ord(c): None for c in string.whitespace})

您也可以使用正则表达式。请查看here 了解更多信息。

【讨论】:

    猜你喜欢
    • 2017-09-06
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2010-11-09
    • 2018-02-11
    相关资源
    最近更新 更多