我正在制作一个python脚本,只是为了好玩,我希望它选择一个随机主题,每次谈论这里是我的代码片段
def randsub():
rand = random.randrange(1,3)
rand.toString()
randsub = "sub" + rand
randsub()
但它一直给我这个错误 TypeError:无法将'int'对象隐式转换为str
答案 0 :(得分:3)
将这些功能放在一个列表中,然后使用random.choice()
function随机选择一个。函数只是对象,就像Python中的任何其他值一样:
import random
def sub_hello():
print('Well, hello there!')
def sub_nice_weather():
print("Nice weather, isn't it?")
def sub_sports():
print('What about them Broncos, eh?')
chat_functions = [sub_hello, sub_nice_weather, sub_sports]
randsub = random.choice(chat_functions)
randsub()
您遇到了特定错误,因为您尝试将整数与字符串连接起来("sub"
是一个字符串,rand
是一个整数);您通常首先将整数转换为字符串,或使用支持将其他对象转换为字符串的字符串模板(如str.format()
或str % (values,)
)。但是,即使字符串 value 与您碰巧定义的函数名相同,字符串也不会变成函数。