python - 如何从 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])
如果您需要更多信息,请询问!
解决方案
这可以简化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)
推荐阅读
- arrays - 在 Ruby 中操作数组的最有效方法是什么
- android - Android进度条不确定
- crystal-reports - Crystalreport for Visual Studio 2019 和 Web 服务器要求
- python - Paramiko - 从 SSH 连接获取一些输出
- git - 签出远程分支后,有没有办法从尚未提交的本地分支的暂存区取回文件?
- javascript - MediaStream 上的网络语音识别
- jquery - 如果任何属性包含值,则jQuery查找元素
- wordpress - Wordpress:在后台设置选项卡中显示选项表中的字段
- python - Pandas 数据框底部的总和行数
- windows - 如何为跨平台测试创建 ODBC“DSN”?