Python: party with Strings
Since Python 3.6 a new way to handle strings has become available. Suppose you have variables:
name = "andy"
age = 42
likes = "Python"
and you want to generate a string that says:
"We know someone called andy who is aged 42 and likes to use Python to program."
It's now simple and elegant to do that using F-Strings.
Here's how it works:
print(f"We know someone called {name} who is aged {age} and likes to use {likes} to program.")
That's it. No type conversion, concatenation, etc. Just start the string with f before the first ", and enclose all variables in {}.
It works anywhere you need to process a string. Give it a try!
Lol the pic cracks me and is a perfect choice on the topic. Thank you for the info!
Good question - print(f"My name is {name}") looks really elegant to me, it doesn’t need the $ and there is a precedent for “qualifying” strings with a preceding character like this across other languages, albeit in other usage situations.
Pretty sure it is recommended to call them all at the end explicitly using the standard lib string format method.
Actually this is the former way to do it before f-strings. The code works as stated. Give it a try in iPython!
I did exactly what you recommended… I tried the code in Ipython/jupyter and it worked like a dream. Thanks.
That’s great to hear! f-strings are very powerful. Great to use in the logging module too.