简体   繁体   English

删除字符串中的“\n”时如何保存“\\n”

[英]How to save " \\n " when removing " \n " in string

>>> b = 'first \\n second \n third \\n forth \n fifth \\n'
>>> print(b)
first \n second 
 third \n forth 
 fifth \n

b to wanted result, b 想要的结果,
print( result )打印(结果)
first \n second third \n forth fifth \n
result = 'first \n second third \n forth fifth \n' result = '第一个\n第二个第三个\n第四个第五个\n'
how to do this?这该怎么做?

\n is an escape character, which indicates a line break, while \\n is a backslash and a letter n , which will not be affected when you delete \n : \n一个转义字符,表示换行,而\\n是一个反斜杠和一个字母 n ,删除\n时不受影响:

>>> b = 'first \\n second \n third \\n forth \n fifth \\n'
>>> b.replace('\n', '')
'first \\n second  third \\n forth  fifth \\n'

This example may make you realize the difference between them:这个例子可能会让你意识到它们之间的区别:

>>> len('\n')
1
>>> list('\n')
['\n']
>>> len('\\n')
2
>>> list('\\n')
['\\', 'n']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM