【问题标题】:How to treat \t as a regular string in python [duplicate]如何在python中将\ t视为常规字符串[重复]
【发布时间】:2014-09-02 11:12:13
【问题描述】:

我需要从正在写入的字符串中删除 \t,但是当我这样做时

str(contents).replace('\t', ' ')

它只是删除了所有选项卡。我知道这是因为 \t 是您编写制表符的方式,但我想知道如何将其视为常规字符串。

【问题讨论】:

    标签: python string python-2.7 replace


    【解决方案1】:

    您可以在字符串前面加上r 并创建一个raw-string

    str(contents).replace(r'\t', ' ')
    

    原始字符串不处理转义序列。下面是一个演示:

    >>> mystr = r'a\t\tb'  # Escape sequences are ignored
    >>> print(mystr)
    a\t\tb
    >>> print(mystr.replace('\t', ' '))  # This replaces tab characters
    a\t\tb
    >>> print(mystr.replace(r'\t', ' '))  # This replaces the string '\t'
    a  b
    >>>
    

    【讨论】:

    • 谢谢,效果很好!!!
    猜你喜欢
    • 1970-01-01
    • 2016-12-10
    • 2021-10-13
    • 2020-10-27
    • 2015-09-12
    • 2011-05-27
    • 2011-05-23
    • 2016-10-30
    • 1970-01-01
    相关资源
    最近更新 更多