如何在打印函数中调用此函数定义?

2024-04-25 21:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python创建了这个函数定义:

def random_person():
    mylist = ["wounded priestress", "crying girl"]
    return random.choice(mylist)

现在我想在我的代码中的打印函数中调用该函数:

print("In the temple, you find a random_person().")

不幸的是,它不会产生我为随机函数选择的字符串。 这就是我得到的:

In the temple, you find a random_person().

2条回答

试试这个

import random
def random_person():
   mylist = ["wounded priestress", "crying girl"]
   return random.choice(mylist)
print(f"In the temple, you find a {random_person()}.")

它使用f字符串的方式比+str()+更好

我只是想编译我在评论中列出的所有选项:)

print(f"In the temple, you find a {random_person()}.") # my personal favorite
print("In the temple, you find a", random_person(), ".")
print("In the temple, you find a {}.".format(random_person()))
print("In the temple, you find a %s." % random_person())

还有“Jean Francois”:

print("In the temple, you find a "+random_person()+".")

相关问题 更多 >