使用print语句时显示特殊字符 [英] Display special characters when using print statement

查看:165
本文介绍了使用print语句时显示特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用print语句时显示转义字符。例如

I would like to display the escape characters when using print statement. E.g.

a = "Hello\tWorld\nHello World"
print a
Hello   World
Hello World

我希望显示:
Hello \tWorld \\\
Hello\sWorld

I would like it to display: "Hello\tWorld\nHello\sWorld"

推荐答案

使用 repr

a = "Hello\tWorld\nHello World"
print repr(a)
# 'Hello\tWorld\nHello World'

请注意,您不能为空间获取 \s 。我希望这是一个错字...?

Note you do not get \s for a space. I hope that was a typo...?

但是,如果你真的想要空格的 \s 你可以这样做:

But if you really do want \s for spaces, you could do this:

print repr(a).replace(' ',r'\s')

这篇关于使用print语句时显示特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆