打印字符串时是否可以显示空格,制表符等特殊字符?

时间:2019-01-31 13:42:12

标签: python string repr

例如,我有一个字符串

line = r'I like cakes'

是否可以这样打印?

 I\s like\s cakes

repr()在这种情况下不起作用

3 个答案:

答案 0 :(得分:3)

一种方法是为要替换的每个字符提供一个替换字典。

rep_dict = {' ': '\s', '\n': '\\n', '\t': '\\t'}

以下功能将执行必要的替换:

def quote(s):
    return "".join(repr_dict.get(c, c) for c in s)

repr_dict.get调用尝试在字典中查找字符,并将字符本身用作失败查找的默认值。

答案 1 :(得分:0)

您可以通过将空格替换为预期的顺序来实现:

Python 3.7.2 (default, Jan 10 2019, 23:51:51) 
[GCC 8.2.1 20181127] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> line = r'I like cakes'
>>> print(line.replace(" ", "\s "))
I\s like\s cakes

要同时支持标签,可以使用:

Python 3.7.2 (default, Jan 10 2019, 23:51:51) 
[GCC 8.2.1 20181127] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> line = "I like\tcakes"
>>> print(line)
I like  cakes
>>> print(line.replace(" ", "\s ").replace("\t", "\\t"))
I\s like\tcakes

答案 2 :(得分:0)

您可以通过Python String replace() Method实现此目标:

line = r'I like cakes'    
print(line.replace(" ", "\s "))

输出:

I\s like\s cakes