0

假设我在 Python 中有以下字符串:

>>> example="""
... \nthird line
... [\t] <-tab in there
... [\n] <-\\n in there
... \v vtab
... 1\b2 should be only '2'
... this\rthat <- should be only 'that'
... """

如果我打印它,各种转义字符(如\t制表符)将被插入到人类可读的形式中:

>>> print example


third line
[   ] <-tab in there
[
] <-\n in there

 vtab
2 should be only '2'
that <- should be only 'that'

如果我只想生成一个带有扩展或解释的各种转义码的字符串而不打印它怎么办?像:

>>> exp_example = example.expandomethod()

(我查看了各种字符串方法、解码和格式,但没有一个像本例那样工作。)


编辑

好的——感谢您对我的厚桨的帮助。我确信这些字符串正在被解析,它们确实如此,但是它们的显示愚弄了我。

我在自己的脑海中解决了这个问题:

>>> cr='\012'   # CR or \n in octal
>>> len(cr)
1
>>> '123'+cr
'123\n'
>>> '123\012' == '123\n'
True
4

4 回答 4

1

它们没有被插值。它们是印刷的。例如,\t通常会打印多个空格;this\rthat将打印this,返回并that在其上打印。如果你要在打印机上打印它,你会看到这两个词。

如果您想将字符串简化为打印等效字符串,我想您必须编写自己的终端仿真器 - 我不知道有任何库可以为您做这件事。

一个更好的问题是——你为什么需要它?它看起来很像一个 XY 问题。

于 2012-12-10T02:25:56.043 回答
1

有些字符的表示与打印时的样子不同。(换行符'\n'只是最明显的一个。)您无法真正存储这些字符在打印时的外观。这就像询问如何存储特定字体使字符看起来的方式。

>>> example="""a
... b"""
>>> print example # This is what a newline looks like. You cannot capture it.
a
b
>>> example # This is how a newline is represented.
'a\nb'
于 2012-12-10T02:30:42.850 回答
1

print 不解释任何东西。它已经是具有不同内部和外部表示的字符串本身。

证明:

s = "\t"
len(s)

...产量1而不是2

于 2012-12-10T02:38:24.653 回答
0

正如其他人所说,当您输入转义字符串时,或者 Python 首先解释该字符串时,转义字符\和后面的字符将减少为单个目标字符。

但是 - 如果您正在构建一个字符串,其目标是从其转义序列中生成不可打印的字符,str.decode([encoding[, errors]])会执行您想要的操作:

>>> s='string'
>>> esc='\\'
>>> n='n'
>>> st=s+esc+n+'next line'
>>> print st
string\nnextline
>>> print st.decode('string_escape')
string
next line

和这个:

>>> ''.join(['\\','n','\\','t'])=='\n\t'
False

与此不同的结果:

>>> ''.join(['\\','n','\\','t']).decode('string_escape')=='\n\t'
True
于 2012-12-12T22:25:46.727 回答