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

Is there a way to add characters based on a variable?

我正在制作一个关于 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)
'_ _ _ _ _ _ _ _ _'

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

首先, 你不需要 wordPlaying = str("Didgeridoo") 只需要 wordPlaying = "Didgeridoo"

wordPlayingLength = int(len(wordPlaying))只是wordPlayingLength = len(wordPlaying)

其次, 要重复字符串,您可以使用 ' _ ' * wordPlayingLength

这是您的程序,其中包含我认为您正在描述的逻辑:

if randomNumber == 10:
    wordPlaying = "Didgeridoo"
    print("{}  letters!".format(len(wordPlaying)))
    print(' '.join('_' * len(wordPlaying)))

我删除了一些不必要的括号和 str()int() 的使用。由于调用字符串或列表的 len() 是一个 constant-time 操作,因此无需在此处使用变量来存储长度。

您需要了解的关键行为是:

  • str.join(),它获取可迭代对象的元素,并通过将可迭代对象的元素与调用它的字符串的内容交错,从中生成一个字符串。
  • integer n * sequence s 运算符 returns 将 sn 个副本加在一起得到的序列。