Reputation: 35
So I'm attempting to randomly choose a string from a list and include a variable at any point in the string.
I've already tried enclosing the string and variable in parenthesis and single quotes and those two havent worked.
test = "mark"
markthings = [(test + "went to the store."), (test, "wants to die."), ("At the store, ", test, " was being a idiot.")]
print(random.choice(markthings))
I expect it to print something like "At the store, mark was being an idiot."
Instead I get, "('At the store,' ,'mark', ' was being a idiot.')
Upvotes: 2
Views: 49
Reputation: 8566
Try this,
import random
test = "mark"
markthings = [(test, "went to the store."), (test, "wants to die."), ("At the store, ", test, " was being a idiot.")]
print(" ".join(random.choice(markthings)))
Upvotes: 0
Reputation: 20490
You accidentally made the last two elements a tuple by using ,
instead of a +
for a concatenated string like you did in the first element.
In [23]: test = "mark"
...: markthings = [(test + "went to the store."), (test, "wants to die."), ("At the store, ", te
...: st, " was being a idiot.")]
In [24]: [type(item) for item in markthings]
Out[24]: [str, tuple, tuple]
Once you change markthings
accordingly to make each element a string, it will work as intended
markthings = [(test + "went to the store."), (test+ "wants to die."), ("At the store, "+ test+ " was being a idiot.")]
You can also make the instantation of markthings
easier by using string formatting, example f-strings
markthings = [f"{test} went to the store.", f"{test} wants to die.", f"At the store, {test} was being a idiot."]
Upvotes: 1