如何避免换行符已经存在于一个字符串中? [英] How to escape line break already present in a string?

查看:171
本文介绍了如何避免换行符已经存在于一个字符串中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,为什么这样做:

  testStr =\\\

testStr = \\+ testStr
print testStr
>>> \

发生?
现在不应该打印 \\\

我知道关于 repr()函数,但我宁愿以另一种方式解决这个问题
如果你能帮助我, / p>

解决方案

输入 testStr =\\\
已经被解释了。所以在下一行,你不能改变他们的解释,因为它已经发生了。这是在词汇分析阶段完成的,所以即使在代码实际上执行。当字符串被分配给你的变量时,两个字符\和n已经没有了 - 只有一个字符 - 新的行字符。


I have a question, why does this:

testStr="\n"
testStr = "\\"+testStr
print testStr
>>> \

happen? Shouldn't it now print \n? I know about the repr() function, but I would rather solve this in another way It would be very kind if you could help me

解决方案

After you type testStr = "\n" the special characters are already being interpreted. So in the next line you cannot change their interpretation as it already has happened. This is being done during lexical analysis stage, so even way before the code is actually executed. When the string is being assigned to your variable the two characters "\" and "n" are already gone - there is only one character - the new line character.

这篇关于如何避免换行符已经存在于一个字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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