我正试图获得这一栏:
Suzuki music
Chinese music
Conservatory
Blue grass
Rock n roll
Rhythm
Composition
Contra
Instruments
采用以下格式:
"suzuki music", "chinese music", "conservatory music", "blue grass", "rock n roll", "rhythm"...
这是我尝试过的:
stuff = [
Suzuki music
Chinese music
Conservatory
Blue grass
Rock n roll
Rhythm
Composition
Contra
Instruments
]
for line in stuff:
list.append("'" + line + "',")
但是我收到了这个错误:
文件“/ private / var / folders / jv / 9_sy0bn10mbdft1bk9t14qz40000gn / T /在启动时清理/ artsplus_format_script-393966065.996.py”,第2行 东西= [ ^ IndentationError:意外缩进 注销
答案 0 :(得分:1)
您正在寻找string.join
功能
对于您的具体示例,代码如下所示:
', '.join(map(lambda x: '"' + x + '"',stuff))
使用the map
function和lambda函数有效地为stuff
集合中的每个元素添加引号。
答案 1 :(得分:1)
假设你在input.txt
:
Suzuki music
Chinese music
Conservatory
Blue grass
Rock n roll
Rhythm
Composition
Contra
Instruments
然后这段代码:
with open('input.txt', 'r') as f:
print ", ".join(['"%s"' % row.lower() for row in f.read().splitlines()])
会打印出来:
"Suzuki music", "Chinese music", "Conservatory", "Blue grass", "Rock n roll", "Rhythm", "Composition", "Contra", "Instruments"