【问题标题】:How can I make strings automatically in Python 3.7?如何在 Python 3.7 中自动生成字符串?
【发布时间】:2019-10-31 10:43:11
【问题描述】:

现在,我正在学习 Python,我想制作一个字典,用户可以在其中添加单词(第一步只是单词,稍后定义)。

word = input('Write a word here')
print('You added ' + word)

所以,我希望用户可以添加更多单词,然后程序将其保存到其他字符串。 我该怎么做?

【问题讨论】:

  • 能否提供一个合适的输出样本。
  • 对于具有 3 个用户输入词作为键和无值的字典:dict.fromkeys(input('Write a word here') for i in range(3))
  • @Chris_Rands:提问者似乎更有可能想要一本字典,而不是 Python 数据结构的字典。 dict 是否合适,以及这样的 dict 可能是什么样子,将取决于他们想要对数据做什么。

标签: python string automation


【解决方案1】:

通常,这可以在 while-loop 中完成,其中循环条件变量会根据用户输入进行更新:

continue_condition = True
words = []

while continue_condition:
    word = input("Write a word here")
    words.append(word)
    continue_condition = input("Would you like to add another word? Then please type `Y`") == "Y"

如果您想填充字典而不是列表,只需根据您的特定需求调整此代码即可。

【讨论】:

    【解决方案2】:

    这将有助于自动化:

    dict = {} # variable to store the key and value 
    
    def add():  # add function to add more word in our dictionary.
        word = input('enter the word:  ') # take the user input
        dict[word] = word;  # this will add the word to our dict for simplicity this is sample so we are using the same key and value.
        if('y' == input('do you want to add more word (y/n): ')): # check if user want to add more word to dictionary.
            add() # if yes the call function again ---recursion.
    
    add() # call function for add word for first time.
    
    print(dict) # print all the words in our dict.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2017-12-13
      相关资源
      最近更新 更多