Kpr*_*ash 5 python string replace python-2.7
我需要从正在写入的字符串中删除 \t 但每当我这样做时
str(contents).replace('\t', ' ')
Run Code Online (Sandbox Code Playgroud)
它只是删除所有选项卡。我理解这是因为 \t 是您编写制表符的方式,但我想知道如何将其视为常规字符串。
小智 5
您可以为字符串添加前缀r
并创建一个raw-string:
str(contents).replace(r'\t', ' ')
Run Code Online (Sandbox Code Playgroud)
原始字符串不处理转义序列。下面是一个演示:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11294 次 |
最近记录: |