如何跳转到python3中的随机函数

时间:2016-02-26 22:37:11

标签: python string python-3.x int

我正在制作一个python脚本,只是为了好玩,我希望它选择一个随机主题,每次谈论这里是我的代码片段

def randsub():
     rand = random.randrange(1,3)
     rand.toString()
     randsub = "sub" + rand
     randsub()

但它一直给我这个错误 TypeError:无法将'int'对象隐式转换为str

1 个答案:

答案 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 与您碰巧定义的函数名相同,字符串也不会变成函数。