如果换行符不在字符串的开头或结尾,我如何删除它们?

问题描述 投票:0回答:2

如何从这个示例字符串中删除\n?(在 Python 3 中)

'Word 1\nWord 2'

我试着用 .带子 但它只能在字符串的开头或结尾删除 \n... ... 我也试过

string.replace('\\n', '')

但似乎也没有用...

python python-3.x replace newline strip
2个回答
3
投票

replace 对我来说是有效的,请确保你做了以下操作。

a = 'Word 1\nWord 2'
a = a.replace("\n", "") #instead of just a.replace("\n", "")

返回: 'Word 1Word 2'


0
投票

你使用的是双 \\ 在这里的新行-> string.replace('\\n', '') 用'"\n "代替


0
投票

将此改为:

string.replace('\\n', '')

替换为 "这个"。

string = string.replace('\n', '') //you used double slashes for some reason

当你使用双斜线时,它认为你要替换这两个字符,而它们是按顺序排列的。\n. 但你要替换的是一个换行符,所以你不需要加上额外的斜杠。


-1
投票
y=""
for x in 'Word 1\nWord 2':
    if(x != "/n"):
       y=y+x
print(y)

你可以使用这段代码,它将打印

Word1
Word2

希望对大家有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.