我正在尝试制作一个游戏,在该游戏中,从文件中选取一首歌名,然后用下划线(除了首个字母之外)替换标题 但是我不确定如何在其中添加空格,因为有些歌曲不止一个字,这就是我目前的情况:
def QuizStart():
line = random.choice(open('songnamefile.txt').readlines())
line.split('-')
songname, artist = line.split('-')
underscoresong = songname
i=0
song_name = range(1,len(songname))
for i in song_name:
if ' ' in song_name:
i=i+1
else:
underscoresong = underscoresong.replace(songname[i],"_")
i=i+1
print(underscoresong, ' - ', artist)
答案 0 :(得分:1)
最好包含给定输入示例的预期输出。
您可以将包含占位符的数组乘以n次。例如:
songname = 'My blue submarine'
underscoresong = ''.join([songname[0]] + ['_'] * (len(songname) - 1))
print(underscoresong)
输出:
M________________
这将添加第一个字符,然后加下划线,只要歌曲名是,减去负号(对于第一个字符)。联接将其转换为字符串。
或者如果您想保留空格:
underscoresong = ''.join(
[songname[0]] + ['_' if c != ' ' else ' ' for c in songname[1:]]
)
print(underscoresong)
输出:
M_ ____ _________
或者如果您还想保留单引号:
songname = "God's Plan-Drake"
underscoresong = ''.join(
[songname[0]] +
['_' if c not in {' ', "'"} else c for c in songname[1:]]
)
print(underscoresong)
输出:
G__'_ __________
您还可以使用正则表达式:
import re
songname = "God's Plan-Drake"
underscoresong = songname[0] + re.sub(r"[^ ']", '_', songname[1:])
print(underscoresong)
输出:
G__'_ __________