【问题标题】:Ampersands are not being replaced with commas in Python text file [closed]在 Python 文本文件中,与号不会被逗号替换 [关闭]
【发布时间】:2016-04-06 21:44:53
【问题描述】:

因为&符号是我要处理的文件中的分隔符,所以我试图用 Python 文本文件中的逗号替换所有&符号的实例,但是下面的代码对文件没有影响。

commafile = open('/ampersandfile.txt')
my_file_contents = commafile.read()
commafile.close()
commafile = open('/csvfile.csv', 'w')
commafile.write(my_file_contents.replace('&', '& ').replace(',  ', ', '))
commafile.close()

【问题讨论】:

  • 您不想用my_file_contents.replace('&', ',') 代替my_file_contents.replace('&', '& ').replace(', ', ', ') 并在csvfile.csv 中检查结果吗?

标签: python csv text


【解决方案1】:

您将 & 号替换为 & 号加一个空格。

使用这个:

Python> "some & text".replace("&", ",")

the docs

返回字符串的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 count,则仅替换第一个 count 出现。

【讨论】:

    【解决方案2】:

    您的.replace() 参数错误。试试这个来替换“&”和“&”。

    commafile.write(my_file_contents.replace('&', ','))
    

    【讨论】:

    • @zondo 这很有道理,我实际上不知道。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多