
With Python, itâs straightforward to reuse variables. Set it once and reuse everywhere, but reusing variables with plain strings isâŠclunky.
Say youâre building a greeting bot. You give the bot a name, and on the screen it prints out a greeting.
name = "Cyn"
print("Hello " + name)Now you want to spice it up by adding another variable: age.
name = "Cyn"
age = 27
print("Hello " + name + " you are " + str(age) + " years old")What if you want to use more than two variables? String concatenation can be a hassle. Youâre tracking + operators and manual type conversions. Values that arenât strings (booleans, ints, floats, dicts, objects) need to be converted into a string or your program crashes!
Writing complex and interesting code will require something more robust than plain strings.
As a lazy productive âš engineer, I believe Python should do most of the work for us. And it can. In Python 3.6, F-strings were introduced and they help us write cleaner code.
What are F-strings?
F-strings are formatted string literals. The âfâ comes from formatted. When you put an f before the quotes, youâre telling Python âevaluate the expressions in curly braces and insert them into the string.â
name = âCynâ
print(fâHello {name}â) # Python evaluates this at runtimeHereâs a resume analyzer. Which version would you rather work with? đđŸ
Plain Strings
# Candidate
name = "Alex Chen" # str
years_experience = 5 # int
desired_salary = 165000.00 # float
location = ("Austin", "US") # tuple
has_degree = True # bool
skills = ["Python", "ML", "Docker"] # list
contact = {"email": "alex@email.com"} # dict
certifications = None # NoneType
# Plain string concatenation
report = "Candidate: " + name + "\n"
report = report + "Experience: " + str(years_experience) + " years\n"
report = report + "Salary Expectation: $" + str(desired_salary) + "\n"
report = report + "Location: " + str(location[0]) + ", " + str(location[1]) + "\n"
report = report + "Has Required Degree: " + str(has_degree) + "\n"
report = report + "Skills: " + str(skills) + "\n"
report = report + "Email: " + str(contact["email"]) + "\n"
report = report + "Certifications: " + str(certifications)
print(report)
This is messy and error-prone. Weâre building line-by-line, manually managing every concatenation and type conversion.
F-Strings
# Candidate
name = âAlex Chenâ # str
years_experience = 5 # int
desired_salary = 165000.00 # float
location = (âAustinâ, âUSâ) # tuple
has_degree = True # bool
skills = [âPythonâ, âMLâ, âDockerâ] # list
contact = {âemailâ: âalex@email.comâ} # dict
certifications = None # NoneType
# F-string
report = fâââCandidate: {name}
Experience: {years_experience} years
Salary Expectation: ${desired_salary}
Location: {location[0]}, {location[1]}
Has Required Degree: {has_degree}
Skills: {skills}
Email: {contact[âemailâ]}
Certifications: {certifications}âââ
print(report)
Python evaluates variables and inserts them automatically. No type conversions, no concatenation.
Life with F-strings
This post only scratches the surface on what f-strings are and how theyâre handy. But thereâs so much more we can do. For instance, we can change the formatting of desired_salary to show only two decimals or call functions within f-strings!
Stay tuned for part 2, and as always, happy coding đ».
