打印一个str的转义表示 [英] Print escaped representation of a str

查看:116
本文介绍了打印一个str的转义表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何打印字符串的转义表示法,例如如果我有:

How do I print the escaped representation of a string, for example if I have:

s = "String:\tA"

我希望输出:

String:\tA

在屏幕上而不是

String:    A

java中的等效功能是:

The equivalent function in java is:

String xy = org.apache.commons.lang.StringEscapeUtils.escapeJava(yourString);
System.out.println(xy);

from Apache Commons Lang

推荐答案

您要使用 string_escape 编码器编码字符串:

You want to encode the string with the string_escape codec:

print s.encode('string_escape')

或者你可以使用 repr()函数,这将把一个字符串变成它的python文字表示,包括引号:

print repr(s)

演示:

>>> s = "String:\tA"
>>> print s.encode('string_escape')
String:\tA
>>> print repr(s)
'String:\tA'

在Python 3中,你'要找 unicode_escape 编解码器:

In Python 3, you'd be looking for the unicode_escape codec instead:

print(s.encode('unicode_escape'))

这将打印一个字节值。要将其恢复为unicode值,只需从ASCII解码:

which will print a bytes value. To turn that back into a unicode value, just decode from ASCII:

>>> s = "String:\tA"
>>> print(s.encode('unicode_escape'))
b'String:\\tA'
>>> print(s.encode('unicode_escape').decode('ASCII'))
String:\tA

这篇关于打印一个str的转义表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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