繁体   English   中英

如何在Python3中将用户输入附加到列表中的项目

[英]How to append user input to an item in a list in Python3

我希望将用户输入加入现有列表中的项目

我尝试使用%s格式化列表中的字符串

from random import randint
user_name = input("Name: ")

我希望%s是用户输入的名称

my_list = ["Hello %s, nice to meet u",  
        "%s! what a wonderful name",
        "welcome %s"]
for m in my_list:
    print(randint(my_list)% user_name)

我的输出应该是列表中与用户输入相伴的任何项目,即输出:#Hello Mike,很高兴认识你

其中“ Mike”是用户输入

我不确定您的代码要表现出什么逻辑意图,但是,这是我对要完成的工作的解释。

from random import randint

user_name = input("Name: ")

my_list = ["Hello %s, nice to meet u",
        "%s! what a wonderful name",
        "welcome %s"]

print(choice(my_list) % user_name)

这将打印列表中的一项(随机),并在所需位置附加输入。

例子:

Name: Tim
Hello Tim, nice to meet u

Name: Pam
Pam! what a wonderful name

Name: Jen
welcome Jen

编辑

使用choice而不是randint来保持清晰/轻松等。

我更习惯于使用长格式字符串。

from random import choice
user_name = input("Name: ")
my_list = ["Hello {name}, nice to meet u",  
        "{name}! what a wonderful name",
        "welcome {name}"]
for m in my_list:
    print(choice(my_list).format(name=user_name))

但是在您的情况下,也可以将randint更改为choice

  • randint返回介于min和max之间的随机数
  • choice随机选择列表中的元素

我认为其他答案更好,但我通过将列表转换为字符串,然后再次转换为列表,做了同样的事情。

from random import randint
user_name = input("Name: ")

my_list = ["Hello %s, nice to meet u",  "%s! what a wonderful name", "welcome %s"]

# convert/flatten the list to string
list_to_string =  "::".join(str(x) for x in my_list)

# Replace %s with the username
replaced_string = list_to_string.replace("%s",user_name )

# convert string to list 
string_to_list = replaced_string.split("::")

print(string_to_list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM