无法逃脱字符串中的转义字符 [英] Can't escape escape characters in string

查看:107
本文介绍了无法逃脱字符串中的转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图回答这个问题,我设法通过转义反斜杠将字符串转到 print 转义字符。

In an attempt to answer this question, I managed to get the string to print the escape characters by escaping the backslash.

当我尝试将其概括为逃避所有转义的字符时,似乎什么都不做:

When I try to generalize it to escape all escaped characters, it seems to do nothing:

>>> a = "word\nanother word\n\tthird word"
>>> a
'word\nanother word\n\tthird word'
>>> print a
word
another word
        third word
>>> b = a.replace("\\", "\\\\")
>>> b
'word\nanother word\n\tthird word'
>>> print b
word
another word
        third word

但是相同的方法对于特定的转义字符,它可以正常工作:

but this same method for specific escape characters, it does work:

>>> b = a.replace('\n', '\\n')
>>> print b
word\nanother word\n    third word
>>> b
'word\\nanother word\\n\tthird word'



<有没有一个一般的方法来实现这一点?应包括 \\\
\t \r 等。

推荐答案

使用r'text定义您的字符串为raw,如下面的代码:

Define your string as raw using r'text', like in the code below:

a = r"word\nanother word\n\tthird word"
print(a)
word\nanother word\n\tthird word

b = "word\nanother word\n\tthird word"
print(b)
word
another word
        third word

这篇关于无法逃脱字符串中的转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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