DEV Community

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

Posted on • Edited on

4.1 String formatting in python Part-1

In this tutorial, you’ll learn the four main approaches to string formatting in Python, as well as their strengths and weaknesses. You’ll also get a simple rule of thumb for how to pick the best general purpose string formatting approach in your own programs.

Let’s jump right in, as we’ve got a lot to cover. In order to have a simple toy example for experimentation, let’s assume you’ve got the following variables (or constants, really) to work with:

errno = 50159747054
name = 'dev'

Based on these variables, you’d like to generate an output string containing a simple error message:

'Hii dev, there is a 0xbadc0ffee error!'

That error could really spoil a dev’s Monday morning… But we’re here to discuss string formatting. So let’s get to work.

1. “Old Style” String Formatting (% Operator)

a) Strings in Python have a unique built-in operation that can be accessed with the % operator.

b) This lets you do simple positional formatting very easily. If you’ve ever worked with a printf-style function in C, you’ll recognize how this works instantly.

Here’s a simple example:

print("Hello, %s" % name)

Output is :

hello, dev

c) I’m using the %s format specifier here to tell Python where to substitute the value of name, represented as a string.

d) There are other format specifiers available that let you control the output format. For example, it’s possible to convert numbers to hexadecimal notation or add whitespace padding to generate nicely formatted tables and reports.

e) Here, you can use the %x format specifier to convert an int value to a string and to represent it as a hexadecimal number:

print('%x' % errno)   # first convert int into string and then hexadecimal value

Output is :

'badc0ffee'

f) The “old style” string formatting syntax changes slightly if you want to make multiple substitutions in a single string. Because the % operator takes only one argument, you need to wrap the right-hand side in a tuple, like so:

print('Hey %s, there is a 0x%x error!' % (name, errno))

Output is :

'Hey dev, there is a 0xbadc0ffee error!'

I’m sure you’ve been wondering why this printf-style formatting is called “old style” string formatting. It was technically superseded by “new style” formatting in Python 3, which we’re going to talk about next.

2. “New Style” String Formatting (str.format)

a) Python 3 introduced a new way to do string formatting that was also later back-ported to Python 2.7. This “new style” string formatting gets rid of the %-operator special syntax and makes the syntax for string formatting more regular.
b) Formatting is now handled by calling .format() on a string object.

Introduction:

Python’s str.format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

This tutorial will guide you through some of the common uses of formatters in Python, which can help make your code and program more readable and user friendly.

Using formatters:

Formatters work by putting in one or more replacement fields or placeholders — defined by a pair of curly braces {} — into a string and calling the str.format() method.

You’ll pass into the method the value you want to concatenate with the string. This value will be passed through in the same place that your placeholder is positioned when you run the program.

Let’s print out a string that uses a formatter:

print('my age is {}'.format(20))

Output is :

my age is 20

a. In the example above, we constructed a string with a pair of curly braces as a placeholder: 'my age is {}'
b. We then added the str.format() method and passed the value of the integer 20 to that method. This places the value of 20 into the string where the curly braces were: my age is 20

We can also assign a variable to be equal to the value of a string that has formatter placeholders:

age='I am {} years old.'
print(age.format('twenty'))

Output is:

I am twenty years old

In this example, we concatenated the string "twenty" with the larger string, replacing the curly braces in the original string.

Using Formatters with Multiple Placeholders :

You can use multiple pairs of curly braces when using formatters. If we’d like to add another variable substitution to the sentence above, we can do so by adding a second pair of curly braces and passing a second value into the method:

strings="my name is {} and i am {} years old"
print(strings.format("DEV","twenty"))

Output is :

my name is DEV and i am twenty years old

To add another substitution, we added a second pair of curly braces into the original string. Then, we passed two strings into the str.format() method, separating them by a comma.

Reordering Formatters with Positional and Keyword Arguments :

  1. When we leave curly braces empty without any parameters, Python will replace the values passed through the str.format() method in order.

As we have seen, so far, a formatter construction with two empty curly braces with two values passed through will look like this:

strings="my name is {} and i am {} years old"
print(strings.format("DEV","twenty"))

Output is :

my name is DEV and i am twenty years old

=>> The first pair of curly braces is substituted with the string value of "DEV", and the second pair is substituted with the string value of "twenty".
The values that exist within the method look like this: ('DEV','twenty')

=>> They are essentially the tuple data type and each individual value contained in the tuple can be called by its index number, which starts with the index number 0.

We can pass these index numbers into the curly braces that serve as the placeholders in the original string:

strings="my name is {0} and i am {1} years old"
print(strings.format("DEV","twenty"))

In the above example, the output will be what we get without passing index numbers into the braces as we are calling the values in the tuple in order:
Output is :

my name is DEV and i am twenty years old

=>> But, if we reverse the index numbers with the parameters of the placeholders we can reverse the values being passed into the string:

strings="my name is {1} and i am {0} years old"
print(strings.format("DEV","twenty"))
my name is twenty and i am DEV years old

=>>If you call an index number of 2 in a tuple that has values at index positions 0 and 1, then you are calling on a value that is out of range. When you call an index number that is out of range, you’ll receive an error message:

strings="my name is {2} and i am {0} years old"
print(strings.format("DEV","twenty"))
IndexError: tuple index out of range


The error message we see refers to the tuple only having values at index numbers 0 and 1, therefore placing index number 2 out of range.

Using Variables :

name='DEV'
age='twenty'
strings="my name is {} and i am {} years old"
print(strings.format(name,age)   # passing the variable defined 

Output

my name is DEV and i am twenty years old
Conclusion

Using formatters for variable substitution can be effective way to concatenate strings and organize values and data. Formatters represent a simple but non-descriptive way for passing variable substitutions into a string, and are useful for making sure output is readable and user friendly.

Thank You

Top comments (3)

Collapse
 
clavinjune profile image
Clavin June

Nice article! But don't forget about the f-prefix strings

Collapse
 
mohit355 profile image
Mohit Raj

Thank You . Now just post a tutorial on it go through this post for F-string.

Collapse
 
mohit355 profile image
Mohit Raj • Edited

Thank you
this will covered in next post.