简体   繁体   中英

How to use a variable in a string when chosing from a list randomly?

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.')

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."]

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)))

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.

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