gpt4 book ai didi

python - 如何在 .csv 文件中转义字符串 Python 2.7 中的逗号

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:40 25 4
gpt4 key购买 nike

我在 .csv 文件中有一个字符串 ven = "the big bad, string"。我需要使用 Python 2.7 转义 , 字符。

目前我正在这样做:ven = "the big bad\, string",但是当我运行以下命令时 print ven,它打印出 the big bad\, string 在终端。

我如何有效地从 .csv 文件中的此字符串中转义 , 字符,这样如果有人要 dl 该文件并在 excel 中打开它就不会把一切都搞砸了?

最佳答案

假设您使用的是 the csv module ,您无需执行任何操作。 csv 为您处理:

import csv

w = csv.writer(open("result.csv","w"))
w.writerow([1,"a","the big bad, string"])

结果:

1,a,"the big bad, string"

但是,如果您没有使用 import csv,那么您需要引用该字段:

row = [1, "a", "the big bad, string"]
print ','.join('"%s"'%i for i in row)

结果:

"1","a","the big bad, string"

关于python - 如何在 .csv 文件中转义字符串 Python 2.7 中的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37219629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com