首页 > 解决方案 > 如何从 for 循环中删除项目?

问题描述

所以我正在尝试制作一个猜谜游戏,您可以使用每个单词的第一个字母来猜测歌曲的名称,我已经记下了第一个单词,但下一个单词总是显示一个额外的“_”有人可以帮忙吗?

import random
import re
sWord = 0
correct = 0
lines = ["All Star-Smash Mouth", "Don't Stop Believin'-Journey", "Mr. Brightside-The Killers"]
song = random.choice(lines)
re.split(r"-", song)
sLists = (song.split("-"))
sList = sLists[0]
sLetter = sLists[0][0]
sWords = sList.split(" ")
sWordAmount = len(sWords)
sOutput = ("")
sGeneration = sList[1:]
for char in sGeneration:
    if char == " ":
        sOutput = sOutput + (" /")
    elif char == "'":
        sOutput = sOutput + (" '")
    elif char == ".":
        sOutput = sOutput + (" .")
    elif char == ",":
        sOutput = sOutput + (" ,")
    elif char == "(":
        sOutput = sOutput + (" (")
    elif char == ")":
        sOutput = sOutput + (" )")
    else:
        for i in range (sWordAmount):
            if char == sWords[i][0]:
                sOutput = sOutput + char
        else:
            sOutput = sOutput + (" _")
print (sLetter + sOutput + " By " + sLists[1])

如果您需要更多信息,请询问!

标签: pythonfor-loop

解决方案


这可以简化isalpha()为使用下划线代替字母,否则保留标点符号。

lines = ["All Star-Smash Mouth", "Don't Stop Believin'-Journey", "Mr. Brightside-The Killers"]
song = random.choice(lines)
name, artist = song.split('-')
s = ''
for word in name.split():
    s += word[0] + ' '.join('_' if l.isalpha() else l for l in word[1:]) + ' /'
print(s[:-1] + ' By ' + artist)

推荐阅读