How to format strings with Python 3

You want to format strings with Python 3? Do you know that’s the most task that we need? like printing text with variables, formatting string uri for database connection and to return messages and errors. With Python 3, f-strings become the great tool to make more readable and faster codes.

But first, lets talk about the str.format() as a function. It takes string and quickly format it with given variables like the example below:

Basic format strings in Python

price = 14.2
currency = '€'
print('The price is {} {}'.format(price, currency))

This example will output The price is 14.2 € the formatted text in one line. We can also index the variable if we need by referencing their index

price = 14.2
currency = '€'
print('The price is {1} {2}'.format(price, currency))

We can give a name to the variables, this may help you in the future when you read your code:

price = 14.2
currency = '€'
print('The price is {a} {b}'.format(a=price, b=currency))

Literal String Interpolation

Using f-string to format strings with Python 3 is more easier with f in the beginning. let’s have a number and string variables user, age = 'bob', 40 and print(f'{user} is {age}) the output is ‘bob is 40’.

If we have a binary data and want to print its value as a binary or hexadecimal value, we can pass options after the value separated by a :. These options are:

“b” : Binary data
“c” : Unicode caracter
“d” : decimal data
“o” : Octal data
“x” : For Hexa

Concatenating strings

String Interpolation can helps us more with concatenations. It’s very hard to concatenate multiple strings with + operator with static strings between variables. With f-string, it becomes very easy and very fast because it’s a run time concatenation. You can also find examples in Files in S3 AWS Python Lambda, how to handle them?

For more details, follow this link

You Might Also Like

Leave a Reply