Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does f string formatting cast a variable into a string? [closed]

Tags:

python

string

I was working with f-strings, and I am fairly new to python. My question is does the f-string formatting cast a variable(an integer) into a string?

number = 10
print(f"{number} is not a string")

Is number cast into a string?

like image 454
Leuel Asfaw Avatar asked Oct 27 '25 05:10

Leuel Asfaw


2 Answers

f"..." expressions format values to strings, integrate the result into a larger string and return that result. That's not quite the same as 'casting'*.

number is an expression here, one that happens to produce an integer object. The integer is then formatted to a string, by calling the __format__ method on that object, with the first argument, a string containing a format specifier, left empty:

>>> number = 10
>>> number.__format__('')
'10'

We'll get to the format specifier later.

The original integer object, 10, didn't change here, it remains an integer, and .__format__() just returned a new object, a string:

>>> f"{number} is not a string"
'10 is not a string'
>>> number
10
>>> type(number)
int

There are more options available to influence the output by adding a format specifier to the {...} placeholder, after a :. You can see what exact options you have by reading the Format Specification Mini Language documentation; this documents what the Python standard types might expect as format specifiers.

For example, you could specify that the number should be left-aligned in a string that's at least 5 characters wide, with the specifier <5:

>>> f"Align the number between brackets: [{number:<5}]"
'Align the number between brackets: [10   ]'

The {number:<5} part tells Python to take the output of number.__format__("<5") and use that as the string value to combine with the rest of the string, in between the [ and ] parts.

This still doesn't change what the number variable references, however.


*: In technical terms, casting means changing the type of a variable. This is not something you do in Python because Python variables don't have a type. Python variables are references to objects, and in Python it is those objects that have a type. You can change what a variable references, e.g. number = str(number) would replace the integer with a string object, but that's not casting either.

like image 55
Martijn Pieters Avatar answered Oct 28 '25 19:10

Martijn Pieters


You can test it yourself quite easily

number = 10
print(f"{number} is not a string")

print(type(number))
# output is integer
like image 40
5idneyD Avatar answered Oct 28 '25 18:10

5idneyD