DEV Community

Cover image for 4.1 String formatting in python Part-2
Mohit Raj
Mohit Raj

Posted on

4.1 String formatting in python Part-2

The new f-strings in Python 3 :-

One of the many goodies packed into the new release are formatted string literals, or simply called “f-strings”.

First, they are called f-strings because you need to prefix a string with the letter “f” in order to get an f-string, similar to how you create a raw string by prefixing it with “r”, or you can use the prefixes “b” and “u” to designate byte strings and unicode strings.

The letter “f” also indicates that these strings are used for formatting.
Now Python already provides several ways for formatting strings, so you may wonder why the Python gods introduced yet another way.

people who overlook the Zen of Python states that simple is better than complex and practicality beats purity - and yes, f-strings are really the most simple and practical way for formatting strings.

To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.

For example:

name='Mohit'
age=20
sentence=f"my name is {name} and i am {age} years old."
print(sentence)

Output is:

my name is Mohit and i am 20 years old.

As you see, this works pretty much like the .format() method, however you can directly insert the names from the current scope in the format string. This is much simpler than the old way, and avoids duplication:

name='Mohit'
age=20
sentence='He said his name is {name} and he is {age} years old.'.format(name=name, age=age)
print(sentence)
He said his name is Fred and he is 42 years old.

Sure, you can omit the names inside the curly braces since Python 3.1, like this:

name='Mohit'
age=20
sentence='He said his name is {} and he is {} years old.'.format(name,age)
print(sentence)

Same output appers:

He said his name is Fred and he is 42 years old.

But still, this is longer and not as readable as the f-string notation.

And it gets even better than this, as f-strings also support any Python expressions inside the curly braces. You can also write triple-quoted f-strings that span multiple lines, like so:

name='mohit'
seven=7
f'''He said his name is {name.upper()} 
and he is {6 * seven} years old.'''

Output is:

'He said his name is MOHIT\n and he is 42 years old.'

=>> F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format().

Top comments (0)