Python字符串替换不起作用的新行
我有一个关键字文件,我只想用逗号替换新行,
print file("keywords.txt", "r").read().replace("\n", ", ")
尝试了 \r\n
的所有变体
I have a keywords file I just wanted to replace the new lines with commas
print file("keywords.txt", "r").read().replace("\n", ", ")
tried all variations of \r\n
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
别忘了,这是Python!始终寻找简单的方法...
', '.join(mystring.splitlines())
Don't forget, this is Python! Always look for the easy way...
', '.join(mystring.splitlines())
您的代码应该按编写的方式工作。然而,这里还有另一种方法。
让 Python 为您分割行(
for line in f
)。使用open
而不是file
。使用with
这样您就不需要手动关闭文件。Your code should work as written. However, here's another way.
Let Python split the lines for you (
for line in f
). Useopen
instead offile
. Usewith
so you don't need to close the file manually.我刚刚尝试过这个,它对我有用。你的文件是什么样的?
我的“temp.txt”文件如下所示:
和我的 python 文件有以下代码:
这是我的输出:
I just tried this and it works for me. What does your file look like?
My "temp.txt" file looked like this:
and my python file had this code:
This was my output:
您编写的代码在我创建的测试文件中适用于我。
您是否正在尝试将结果写回到文件中?
您可以尝试在十六进制编辑器中查看输入文件以查看行结尾。
The code you wrote works for me in a test file I created.
Are you trying to write the results back to a file?
You could try looking at the input file in a hex editor to see the line endings.
您想替换实际的文件内容吗?像这样:
Did you want to replace the actual file contents? Like this:
我刚刚遇到了同样的问题,这是解决方案:
I've just had the same problem and this was the solution to it:
我也遇到了这个问题并用以下方法解决:
我的“\n”在我的单元测试(以 str 作为输入)和我的集成测试(以文件读取导入作为输入)之间没有以相同的方式解释,所以 str.replace ("\n", ",") 不适用于这两个测试。
编辑=>这两种方法都有效:
我不知道为什么 file 和 str 输入之间存在不同...
I had this problem too and solve it with :
My "\n" wasn't interpreted in the same way between my unit test (with str as input) and my integration test (with file reading import as input), so str.replace("\n", ",") didn't work with both tests.
EDIT => With both this works too :
I don't know why is it different between file and str input...
使用双斜杠 n 而不是 \n 进行搜索。这花费了我一生的时间。当我尝试粘贴它时,该网站甚至将其更改为 \n 。不该说的组合。 “”+“”+“n”将是尝试解释它的字符串组合。
Search on double slash n instead of \n. That cost hours of my life. This website even changes it to \n when I tried to paste it. The combo that shall not be spoken. ""+""+"n" would be the string combo to try to explain it.