0

我正在尝试获取这一列单词:

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/Cleanup At Startup/artsplus_format_script-393966065.996.py”,第 2 行内容 = [ ^ IndentationError:意外缩进注销

4

2 回答 2

1

您正在寻找string.join功能

对于您的具体示例,代码如下所示:

  ', '.join(map(lambda x: '"' + x + '"',stuff))

将该map函数与 lambda 函数一起使用可以有效地在集合中的每个元素周围加上引号stuff

于 2013-06-26T19:03:49.573 回答
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"
于 2013-06-26T19:07:34.047 回答