简体   繁体   English

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

[英]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.

相关问题 如何从我的随机二进制字符串中删除换行符? - How can I remove newlines from my random binary string? 如何添加到numpy数组的末尾并从头开始删除? - How can I add to the end of a numpy array and remove from the beginning? 如何在 Python 中删除字符串开头或结尾的停用词? - How to remove stopwords at the beginning or the end of a string in Python? Python字符串清理:如何删除python中多余的换行符? - Python string clean up: How can I remove the excess of newlines of a string in python? 如何从字符串的开头和结尾删除字符,而不是从中间删除? - How do I remove characters from the beginning and end of a string, but not from the middle? 如果 Pandas 中字符串的开头和结尾处可用,如何有效地删除字符? - How to effeciently remove character if available at the beginning and end of a string in Pandas? 如何使用python从文件的开头和结尾删除特定数量的字节? - How can I remove a specific number of bytes from the beginning and end of a file using python? 如何删除字符串的开头 - How to remove beginning of a string 删除所有不是一周开始或结束的行 - Drop All Rows That Aren't The Beginning or End of Week 如何删除可能出现在字符串列值开头或结尾的货币字符? - How can I strip a currency character that may appear in the beginning or end of a string column value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM