4 Python String Formatting Every Python Developer should Master

4 Python String Formatting Every Python Developer should Master

Coming so far with programming, we know, the string is a set of characters. And no doubt, it is one of the most useful data types in any programming language.

What is Python String Formatting?

Instead of using a string as it is, many times we need to stuff the string with other data value. And it is called as string formatting.

You will learn more about it as I explain string formatting with an example below.

In this tutorial, you will also learn to use different approaches for string formatting in Python.

Table of contents

  1. String Formatting using % Operator
  2. String Formatting using str.format()
  3. (Python 3.6+) String Formatting using f-Strings
  4. Template Strings (Standard Library)

To make the best use of this tutorial and mastering string formatting, open your Python interpreter and try running commands as we go with this tutorial.

So, without squandering any further time, let’s discuss now.

1) String Formatting using % Operator

This is the oldest string formatting method.

>>> lang = 'Python'
>>>'You are working with %s' % lang
"You are working with Python"

Here, we are substituting string value. %s is a format specifier for string data. Other than string, you can substitute any other data types as well.

Below is an example where the hexadecimal value is substituted.

>>> noErr = 45565
>>> '%x' % errno
'b1fd'

%x is a format specifier for hexadecimal data. With this format specifier, you can convert an integer value into the hex decimal value and then formate it into the string.

Always print hexadecimal values in the standard format by appending “0x” before the hexadecimal string. It makes easy for the end user to identify the formatting of data value.

If there are multiple substitutions or if you want to stuff multiple values into the single string, you need to pass those values as tuple elements.

>>> lang = 'Python'
>>> noErr = 45565
>>> 'You are working with %s. Please refer 0x%x error.' % (lang, noErr)
'You are working with Python. Please refer 0xb1fd error.'

You can also pass multiple substitute variables using dictionary name-value pair.

>>> lang = 'Python'
>>> noErr = 45565
>>> 'You are working with %(lang)s. Please refer 0x%(noErr)x error.' % {
... "lang": lang, "noErr": noErr}
'You are working with Python. Please refer 0xb1fd error.'

Here you don’t need to worry about the sequence of substitute variables.

2) String Formatting using str.format()

You can call the format method using the str string object.

>>> lang = 'Python'
>>> ''You are working with  {}'.format(lang)
'You are working with Python'

With this approach, passing the name-value pairs as an argument to the format method is easy.

>>> lang = 'Python'
>>> noErr = 45565
>>> 'You are working with {lang}. Please refer {noErr:x} error.'.format( 
... lang=lang, noErr=noErr)
'You are working with Python. Please refer 0xb1fd error.'

3) String Formatting using f-Strings (Python 3.6+)

It is also called as String Interpolation.

Note: f-string formatting approach is new. And it only works with the Python 3 having version 3.6 or higher.

>>> lang = 'Python'
>>> f'You are working with {lang}.'
You are working with Python.

How to Evaluate Expression in Python String Formatting?

You can also evaluate mathematical operations inside the f-string. It is more like embedding Python expressions inside the string to evaluate and print the result.

>>> p = 11
>>> q = 9
>>> f'Addition of two number is {p + q} and multiplication is {p * q}.'
Addition of two number is 20 and multiplication is 99.'

If you need to evaluate numerical data types expression and substitute result into the string, use this method.

4) Template Strings (Standard Library)

So another approach you can use and it is called as a template string. You need to import the Template module from a string.

First, make the template object using Template(). You can format the substitution variable names by prefixing $ sign. And then substitute the value for the variable.

>>> name = Alice
>>> from string import Template
>>> t = Template('My name is $name.')
>>> t.substitute(name=name)
'My name is Alice.'

That’s it all from Python string formatting tutorial. If you give an attention and try to run commands for each formatting approach, this topic is not much difficult.

Other Python String Tutorials:

You can keep this string formatting list handy and use it as per your requirement.

Let me know your opinion using different string formatting. Which formatting do you prefer? Write your experience in the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *