[英]How can I remove newlines if they aren't at the beginning or at the end of a string?
How can I remove \n from this example string?如何从此示例字符串中删除 \n ? (In Python 3)
(在 Python 3 中)
'Word 1\nWord 2'
I tried using .strip but it can only remove \n if its at the beginning or at the end of the string... I also tried:我尝试使用.strip但它只能删除 \n 如果它位于字符串的开头或结尾...我也尝试过:
string.replace('\\n', '')
But that doesn't seem to work either...但这似乎也不起作用......
replace
worked for me, make sure you did the following: replace
为我工作,请确保您执行了以下操作:
a = 'Word 1\nWord 2'
a = a.replace("\n", "") #instead of just a.replace("\n", "")
Returns: 'Word 1Word 2'
返回:
'Word 1Word 2'
you are using double \\
on newline here-> string.replace('\\n', '')
use '"\n"' instead您在此处的换行符上使用双
\\
-> string.replace('\\n', '')
改用 '"\n"'
Replace this:替换这个:
string.replace('\\n', '')
with this:有了这个:
string = string.replace('\n', '') #you used double slashes for some reason
When you uses the double slashes, it thought you were looking to replace these two characters when they're in order: \n
.当您使用双斜杠时,它认为您正在寻找按顺序替换这两个字符:
\n
。 But you want to replace a newline, so you don't need to add the extra slash.但是你想替换一个换行符,所以你不需要添加额外的斜杠。
y=""
for x in 'Word 1\nWord 2':
if(x != "/n"):
y=y+x
print(y)
You can use this code it will print您可以使用它将打印的此代码
Word1
Word2
Hope this might be helpful.希望这可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.