Python F-Strings
F-strings were introduced in Python 3.6 as an improved way of formatting strings and string concatenation. Before f-strings, we would either have to concatenate a bunch of strings using the plus sign (+
) or use the str.format()
method. Both of them aren't particularly elegant. So, f-strings were made as a feature to fix both of them. Using them is similar to using the format()
method, but we simply use the names of variables instead of passing in the variables explicitly as keyword arguments into the str.format()
method. For example, instead of writing:
name = "John"
age = 36
txt = "Hello! My name is {name}. I'm {age} years old.".format(name = name, age = age)
We could write:
name = "John"
age = 36
txt = f"Hello! My name is {name}. I'm {age} years old."
Keep in mind that f-strings were only added in Python 3.6, so f-strings will only work if your Python version is above Python 3.6!
Both of the codes return:
Hello! My name is John. I'm 36 years old.