I want user input to be joined to an item in an existing list
I tried formating the string in the list using %s
from random import randint
user_name = input("Name: ")
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)
my output should be any of the items in the list accompanied by the user input ie output: #Hello Mike, nice to meet u
where "Mike" is the user input
I am not sure what the logic your code is exhibiting is intended to do, however, here is my interpretation of what you want done.
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)
This will print one of the items from the list (at random) with the input appended in the desired location.
Examples:
Name: Tim
Hello Tim, nice to meet u
Name: Pam
Pam! what a wonderful name
Name: Jen
welcome Jen
Utilize choice
instead of randint
for clarity/ease/etc.
I'm more used to using long format strings.
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))
But changing your randint
to choice
should also work in your case.
randint
return a random number between min and max choice
randomly choose an element in a list I think other answers are better but I did the same thing by converting the list to string and then again to list.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.