【问题标题】:Python string replace not working new linesPython字符串替换不起作用的新行
【发布时间】:2011-10-19 18:20:16
【问题描述】:

我有一个关键字文件,我只想用逗号替换新行

print file("keywords.txt", "r").read().replace("\n", ", ")

尝试了\r\n的所有变体

【问题讨论】:

  • 正如发布的那样,您的代码很好。 replace() 最常见的错误是人们忘记分配结果:s.replace(old, new) 而不是 s=s.replace(old, new)。

标签: python string replace


【解决方案1】:

别忘了,这是 Python!始终寻找简单的方法...

', '.join(mystring.splitlines())

【讨论】:

  • 我很确定“pythonic”并不意味着“可能的最短单行”。此外,您的示例甚至没有针对文件运行。
【解决方案2】:

您的代码应该按照所写的方式工作。但是,这是另一种方式。

让 Python 为您拆分行 (for line in f)。使用open 而不是file。使用with,这样你就不需要手动关闭文件了。

with open("keywords.txt", "r") as f:
    print ', '.join(line.rstrip() for line in f) # don't have to know line ending!

【讨论】:

    【解决方案3】:

    我刚试过这个,它对我有用。你的文件是什么样的?

    我的“temp.txt”文件如下所示:

    一个
    b
    c
    d
    e

    我的 python 文件有这个代码:

    print file("temp.txt", "r").read().replace("\n", ", ")
    

    这是我的输出:

    >python temp_read.py
    a, b, c, d, e,

    【讨论】:

      【解决方案4】:

      您编写的代码在我创建的测试文件中适用于我。

      您是否尝试将结果写回文件?

      您可以尝试在十六进制编辑器中查看输入文件以查看行尾。

      【讨论】:

        【解决方案5】:

        您想替换实际的文件内容吗?像这样:

        newContent = file("keywords.txt", "r").read().replace("\r", "").replace("\n", ", ")
        open("keywords.txt", "w").write(newContent)
        

        【讨论】:

          【解决方案6】:

          我刚刚遇到了同样的问题,这是解决它的方法:

          phones = arr[8].replace("\\n", "|")
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-06-24
            • 2019-01-08
            • 2016-02-15
            • 2016-10-05
            相关资源
            最近更新 更多