f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using the __format__ protocol
Here are some of the ways f-strings can make your life easier.
name = "Eric" age = 74 print(f"Hello, {name}. You are {age}.") #Output: 'Hello, Eric. You are 74.' print(F"Hello, {name}. You are {age}.") #Output: 'Hello, Eric. You are 74.' |
Both f & F are valid to form a f-strings
Because f-strings are evaluated at runtime, you can put any and all valid Python expressions in them.You could do something pretty straightforward, like this:
print(f"{10 + 20}") #Output: 30 print(f"{10 - 20}") #Output: -10 print(f"{10 * 20}") #Output: 200 print(f"{10 / 20}") #Output: 0.5 print(f"{10 % 20}") #Output: 10 |
you could also call functions. Here’s an example:
def sum_two_numbers(a , b): return a + b a = 10 b = 20 print(f"Sum of two number is {sum_two_numbers(a, b)}") #Output: Sum of two number is 30 |
You could even use objects created from classes with f-strings. Imagine you had the following class:
class myclass_summ: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return f"Sum of two values is {self.a + self.b}." def __repr__(self): return f"Sum of two values is {self.a + self.b}. Surprise!" sum_obj = myclass_summ(10, 20) print(sum_obj) #Output: Sum of two values is 30. |
The __str__() and __repr__() methods deal with how objects are presented as strings, so you’ll need to make sure you include at least one of those methods in your class definition. If you have to pick one, go with __repr__() because it can be used in place of __str__().
The string returned by __str__() is the informal string representation of an object and should be readable. The string returned by __repr__() is the official representation and should be unambiguous. Calling str() and repr() is preferable to using __str__() and __repr__() directly.
By default, f-strings will use __str__(), but you can make sure they use __repr__() if you include the conversion flag !r:
class myclass_summ: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return f"Sum of two values is {self.a + self.b}." def __repr__(self): return f"Sum of two values is {self.a + self.b}. Surprise!" sum_obj = myclass_summ(10, 20) print(f"{sum_obj!r}") #Output: Sum of two values is 30. Surprise! |
name = "John" profession = "Software Engineer" country = "US" message = ( f"Hi {name}. " f"You are a {profession}, " f"living in {country}." ) print(message) #Output: Hi John. You are a Software Engineer, living in US. |
Note: you need to place an f in front of each line of a multiline string otherwise it won't work
If you want to spread strings over multiple lines, you also have the option of escaping a return with a \:
name = "John" profession = "Software Engineer" country = "US" message = f"Hi {name}. " \ f"You are a {profession}, " \ f"living in {country}." print(message) #Output: Hi John. You are a Software Engineer, living in US. |
The f in f-strings may as well stand for “fast.” f-strings are faster than both %-formatting and str.format(). As you already saw, f-strings are expressions evaluated at runtime rather than constant values
At runtime, the expression inside the curly braces is evaluated in its own scope and then put together with the string literal part of the f-string. The resulting string is then returned. That’s all it takes.
You can use various types of quotation marks inside the expressions. Just make sure you are not using the same type of quotation mark on the outside of the f-string as you are using in the expression.
print(f"{'Hello World'}") #Output: Hello World print(f'{"Hello World"}') #Output: Hello World print(f"""Hello World""") #Output: Hello World print(f'''Hello World''') #Output: Hello World |
If you find you need to use the same type of quotation mark on both the inside and the outside of the string, then you can escape with \:
a = b = 10 result = a + b print(f"Sum of \"a\" & \"b\" is {result}.") #Output: Sum of "a" & "b" is 20. |
when you are working with dictionaries. If you are going to use single quotation marks for the keys of the dictionary, then remember to make sure you’re using double quotation marks for the f-strings containing the keys.
numbers = {'a': 10, 'b': 20} print(f"Sum of {numbers['a']} & {numbers['b']} is {numbers['a'] + numbers['b']}.") # Output: Sum of 10 & 20 is 30. |
If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!