Python使用函数作为字符串[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我想将一个函数用作String,我有这个函数:

def getCoins(user):     ##Get the Coins from a user.##
    try:
        with open(pathToUser + user + ".txt") as f:
            for line in f:
                print(user + " has " + line +" coins!")
    except:
        print("Error!")

现在它只是打印硬币,但我想在其他代码中使用它,如下所示:

client.send_msg(m.text.split(' ')[2] + "has" + coinapi.getCoins('User') + "coins")

怎么做?所以我可以像字符串一样使用它,Twitchchat中的消息应该是:

"USERXYZ has 100 coins"
python string function
2个回答
1
投票

返回一个字符串

def getCoins(user):     ##Get the Coins from a user.##
    try:
        with open(pathToUser + user + ".txt") as f:
            return '\n'.join(user+" has "+line +" coins!" for line in f)
    except:
        return "Error!"

你也应该使用格式字符串(假设python 3.6)

def getCoins(user):     ##Get the Coins from a user.##
    try:
        with open(f"{pathToUser}{user}.txt") as f:
            return '\n'.join(f"{user} has {line} {coins}!" for line in f)
    except:
        return "Error!"

0
投票

您应该能够在输出中返回所需的字符串。看起来你的代码正在迭代f并打印每行上的硬币数量,所以你可能需要返回硬币数量的列表或生成器,但你问题的关键答案就是返回一个字符串或者某个东西。可以变成一个字符串

© www.soinside.com 2019 - 2024. All rights reserved.