It’s unclear what the big advantage is over `print("Age: "+age)`. It’s even more characters, in that specific example.
back
3 comments
>>> age = 32
>>> print("Age: " + age)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> print("Age: " + str(age))
Age: 32
As a side note, I always found it amusing that Python is dynamic but doesn't let you do this, while C# has static typing but lets you do string + number. (I looked into it a while back, I think it's because both are Object, so it does operator overloading on Object+Object and then checks the types...)Toy examples aren’t the use case, rather multiple variables or expressions, perhaps with formatting (padding) as well.
f-string is shorter, less err prone, and faster for medium complexity or above.
If age is a number, that won’t work.
Admittedly I’m not so familiar with Python; it does work in Java. In that case, introducing a less hazardous string concatenation operator would seem more universally useful.
In Python, that less hazardous string concatenation operator is an f-string.
I’m assuming you can only use it with string literals, hence it is less universally useful.
Nope, you can put expressions in them:
f'{a} = {functionThatReturnsAButHasSideEffects()}'