Search code examples
pythonstringconcatenationf-string

does the f-string convert an integer to a string?


Hello I was practicing using loops and I saw that while using concatenation I have to convert int's to strings, but then I saw that if I use a f-string I dont need convert it to an int.

Here is the code:

# some code up there

average_cost = [total_cost / len(actual_insurance_costs)]

# using a f-string
print(f"Average Insurance Cost: {average_cost} dollars.")

# using concatenation
print("Average Insurance Cost: " + str(average_cost) + " dollars.")

So does the f-string convert an int into a string?


Solution

  • Yes, it does, by way of calling format(...) on it, which in turn calls __format__() on the object.

    That extends to everything else too, including objects with a custom __format__(). For instance,

    class Thing:
        def __format__(self, format_spec):
            return f"I don't like being formatted with {format_spec!r}!"
    
    
    print(f"This is a thing: {Thing():>10}")
    

    prints out

    This is a thing: I don't like being formatted with '>10'!
    

    (The default implementation of __format__() just calls __str__().)