【问题标题】:How to jump to a random function in python3如何在python3中跳转到随机函数
【发布时间】:2016-02-26 22:37:11
【问题描述】:

我正在制作一个 python 脚本,它只是为了好玩而回话,我希望它每次都随机选择一个话题来谈论这里是我的代码的 sn-p

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

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

【问题讨论】:

    标签: python string python-3.x int


    【解决方案1】:

    将函数放在一个列表中,然后使用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 与您碰巧定义的函数名称相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2011-07-14
      相关资源
      最近更新 更多