AppDividend
Latest Code Tutorials

Python f Strings | An Improved String Formatting in Python 3

0

Formatting String in Python is one of the most repetitive tasks you have faced while in development. As of 3.6 version, Python f-strings is a comprehensive new way to format strings. Not only are they more readable, they are also more concise but also less prone to error than other ways of formatting, and also they are faster!

Old ways to Format the String in Python

Before Python 3.6 release, you had two main ways of embedding Python expressions inside string literals for formatting:

  1. %-formatting
  2. str.format()

Using %-formatting

String objects have an inbuilt modulo % operator, which you can use to format strings.

xoxo = 'Weeknd'
print('Hello, %s' % xoxo)

Output

Hello, Weeknd

In this example, we have printed the xoxo string in the print statement. Now, inside the print statement, we have used the %s, which act as a string placeholder for the variable. And then used the modulo % operator with our string variable.

The %-formatting is not recommended by the python docs, which include the following note.

“The formatting operations described here exhibit the variety of quirks that lead to several common errors (such as failing to display the tuples and dictionaries correctly).

Using a newer formatted string literals or the str.format() method helps avoid these errors. These alternatives also provide more robust, flexible, and extensible approaches to format the text.” (Source)

Formatting more than one variable

To add more than one variable, you must use the tuple of those variables.

xoxo = 'Weeknd'
yello = 'Homer'
print('Hello, %s and %s' % (xoxo, yello))

Output

Hello, Weeknd and Homer

From the above examples, you can see that the Code is readable, but we still don’t use this because once you start using several parameters and longer strings, your Code will quickly become much less easily readable. That is why the Python community does not recommend this approach.

Using str.format()

The str.format()  is an improvement on %-formatting. The str.format() works as a normal function that you call and is extendable through the __format__() method on the object being converted to the string. With the str.format() method, the replacement fields are marked by curly braces and that curly braces will be replaced by string variables.

xoxo = 'Weeknd'
yello = 'Homer'
print('Hello, {} and {}'.format(xoxo, yello))

Output

Hello, Weeknd and Homer

You can see that the Code is very concise and clear regarding using the variables in the string. We have replaced the two curly braces with two variables xoxo and yello.

Refer variables by index

You can reference the variables in any order by referencing their index.

xoxo = 'Weeknd'
yello = 'Homer'
print('Hello, {0} and {1}'.format(xoxo, yello))

Output

Hello, Weeknd and Homer

In this example, we have passed 0 and 1. Now, this is about the arguments you pass in the format() function. So, if you give 0 means the first argument of the format will be returned. 1 Means second, and so on.

But if you add the variable names, you get the advantage of being able to pass the objects and then reference parameters and methods in between the braces.

data = {'xoxo': 'Weeknd', 'yello': 'Homer'}
print('Hello, {xoxo} and {yello}'.format(xoxo=data['xoxo'], yello=data['yello']))

Output

Hello, Weeknd and Homer

There also another neat way to reference the parameters of Dictionary. The ** method. You just have to pass the **dictionary_name in the format() function, and you are good to go. But make sure that you reference the dictionary keys in the curly braces.

data = {'xoxo': 'Weeknd', 'yello': 'Homer'}
print('Hello, {xoxo} and {yello}'.format(**data))

Output

Hello, Weeknd and Homer

We get the same output.

Again, Code using str.format() is much more easily readable than Code using %-formatting, but str.format() function can still be quite lengthy when you are dealing with multiple parameters and longer strings. See the following Code.

Python f String: An Improved Way to Format Strings

Python f String is an improvement over previous formatting methods. You can read more at PEP8. Also called “formatted string literals,” f-strings are string literals that have an f at the starting and curly braces containing the expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using a __format__ protocol.

Syntax

The syntax is similar to the one you used with str.format() but less gabby.

print(f'{}')

Example

xoxo = 'Weeknd'
yello = 'Homer'
print(f'Hello, {xoxo} and {yello}')

Output

Hello, Weeknd and Homer

In this Code, we don’t have to write format() function anymore; instead, f or F would suffice.

xoxo = 'Weeknd'
yello = 'Homer'
print(F'Hello, {xoxo} and {yello}')

Output

Hello, Weeknd and Homer

You can see that we have not used small-cap f. Instead, we have used capital F, and we did not get any error that means F is a valid syntax.

f-strings in Python are evaluated at runtime, and you can put valid Python expressions in them. This enables you to do some nifty things.

xoxo = 'Weeknd'
yello = 'Homer'
print(f'{5 + 6}')

Output

11

You can also call functions.

def add(a, b):
    return a + b


print(f'The sum is: {add(19, 21)}')

Output

The sum is: 40

You can see that we got the output from the add() function, which is the sum of a and b parameter.

You can also call the method directly. Let’s say we will call an inbuilt Python sum() method and see if we get the correct output.

list = [1, 2, 3, 4, 5]

print(f'The sum is: {sum(list)}')

Output

The sum is: 15

Multiline f-Strings

Python provides various ways to create a multiline string. It can be useful when you have a very long string, and you can divide that string into multiline.

In Python, you can have multiple f-strings as well.

language = 'Python'
salary = '100k'
work = 'Remote'

data = (f'{work} '
        f'{language} developer salary is '
        f'{salary}')

print(data)

Output

Remote Python developer salary is 100k

In this example, we have defined three variables, and each variable is written on the individual line. You can see that rounded brackets enclose the multiline string. This is one of the ways to write multiline strings in Python. But remember that you need to place an f in front of each line of a multiline string.

If you don’t put the f in front of each line, then you’ll just have regular, old strings and not shiny, fancy f-strings.

If you want to spread strings over the multiple lines, you also have the option of escaping a return with a \.

Python f-strings are faster than both %-formatting and str.format(). The f-strings are expressions evaluated at runtime rather than constant values.

Dictionaries in f-strings

You can use different 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"{'Homer Simpson'}")

Also please watch out when you are working with dictionaries. If you are going to use the single quotation marks for the keys of the Dictionary, then remember to make sure you are using the double quotation marks for the f-strings containing the keys.

data = {'student': 'Taylor', 'enrollment': 21}

print(
    f"The student is {data['student']} and its enrollment is {data['enrollment']}")

Output

The student is Taylor and its enrollment is 21

If you use the same type of quotation mark around the dictionary keys as you do on the outside of the f-string, then the quotation mark at the beginning of the first dictionary key will be interpreted as the end of the string. In our example, the outer quotes are double quotes, and inner quotes for dictionary keys are single quotes.

Conclusion

You can still use the older approaches of formatting strings, but with Python f-strings, you now have a more short, readable, and convenient way that is both faster and less prone to error. Simplifying your life by using the f-strings is a great reason to start using Python 3.6 if you haven’t already made the switch.

Finally, Python f strings example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.