简体   繁体   中英

How can I return both a string and an integer value from a method?

I am having a hard time figuring out how to return my function with a "%" sign.

Here is what I have:

def calculate(string):
    A = string.count("A")
    D = string.count("D")
    x = A + D
    answer = (x / len(string)) * 100
    return int(answer)

I want it to return the final answer, but with a percentage sign next to it, like '65%' for example

I tried these:

return int(answer) + "%"
return int(answer) and "%"

but none of those really worked and it gave me an error.

For a single returned value: you can't

The problem is that int(answer) is a number and '%' is a string, so you cant combine these in a return value - unless you convert both to the same data type.

Try converting both values to a string:

return "{}%".format(int(answer))

You could go totally overboard and define your own integer type that displays itself with a percent symbol:

class pint(int):
    def __str__(self):
        return super().__str__() + '%'
    __repr__ = __str__

You can now make the return value of your function be pint(answer) and reap the benefits of having your number actually be a number while always printing as a percentage.

I don't really recommend this approach for your trivial case, but it could have its uses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM