用引号将单词列表中的一列单词用逗号隔开

2024-09-28 03:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到这一栏的文字:

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\u sy0bn10mbdft1bk9t14qz40000gn/T/Cleanup At Startup/artsplus\u format\u script-393966065.996.py”,第2行 材料=[ ^ 缩进错误:意外缩进 注销


Tags: 错误linemusicbluegrassrollcompositionrock
2条回答

假设您在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"

您正在寻找^{}函数

对于您的特定示例,代码如下所示:

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

使用the ^{} function和lambda函数可以有效地在stuff集合中的每个元素周围加引号。你知道吗

相关问题 更多 >

    热门问题