Skip to main content
 首页 » 编程设计

python之有没有办法根据变量添加字符

2024年11月24日7落叶无声

我正在制作一个关于 Hangman 的基于文本的游戏,到目前为止,我有 10 个单词,每个单词中的字符数量不同。最少的字符数是三个,所以我计划在开头添加三个下划线,以便能够在字符串后添加下划线。

我设置了一个名为 wordPlayingLength 的变量,它根据通过随机语句选择的单词中的字符数计算一个整数。我的问题是是否有办法添加与单词字符长度相匹配的下划线?

if (randomNumber == 10): 
    wordPlaying = str("Didgeridoo") ## states the word being played 
    wordPlayingLength = int(len(wordPlaying)) ## calculates the character length of the word being played 
    print(str(wordPlayingLength) + " letters!") 
 
    underscoreCount = (wordPlayingLength) 
    print("_ _ _ " + ) ## this is where I got stuck, no idea here 

请您参考如下方法:

在 Python 中,您可以将一个字符串乘以一个整数来进行重复:

>>> num_of_underscores = 9 
>>> num_of_underscores * "_" 
'_________' 

如果你想要下划线之间有空格,你可以这样做

>>> " ".join("_" * num_of_underscores) 
'_ _ _ _ _ _ _ _ _' 

将带有单个下划线的数组乘以一个整数,得到那么多数组。