The Wayback Machine - https://web.archive.org/web/20210122155245/https://www.geeksforgeeks.org/string-formatting-in-python/
Related Articles

Related Articles

String formatting in Python
  • Last Updated : 20 Aug, 2020

A String is usually a bit of text that you want to display or to send it to a program and to infuse things in it dynamically and present it, is known as String formatting.

There are three different ways to perform string formatting:-

  • Formatting with placeholders.
  • Formatting with.format() string method.
  • Formatting with string literals, called f-strings.

So we will see the entirety of the previously mentioned ways, and we will also focus on which string formatting strategy is the best.

Formatting with Placeholders

It is the oldest method of string formatting. Here we use the modulo % operator. The modulo % is also known as “string-formatting operator”.

Example:



Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print("The mangy, scrawny stray dog %s gobbled down" + 
      "the grain-free, organic dog food." %'hurriedly')

chevron_right


Output:

The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic dog food.

You can also inject multiple strings at a time and can also use variables to insert objects in the string.

Example:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

x = 'looked'
  
print("Misha %s and %s around"%('walked',x))

chevron_right


Output:

Misha walked and looked around.

‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for floating-point values, ‘%b’ for binary format. For all format conversion methods visit the official documentation.

Example:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print('Joe stood up and %s to the crowd.' %'spoke')
  
print('There are %d dogs.' %4)

chevron_right


Output:



Joe stood up and spoke to the crowd.
There are 4 dogs.

Float precision with the placeholder method:

Floating-point numbers use the format %a.bf. Here, a would be the minimum number of digits to be present in the string; these might be padded with white space if the whole number doesn’t have this many digits. Close to this,.bf represents how many digits are to be displayed after the decimal point. 

Let us see a few examples:

Example 1:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print('The value of pi is: %5.4f' %(3.141592))

chevron_right


Output:

The value of pi is: 3.1416

Example 2:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print('Floating point numbers: %1.0f' %(13.144))

chevron_right


Output:

Floating point numbers: 13

Note: You can use multiple format conversion types in a single print statement.

Formatting with the.format() string method

This method was introduced in Python 3 was later also introduced to Python 2.7. Formatting is now done by calling.format() method. 

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)



Example:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print('We all are {}.'.format('equal'))

chevron_right


Output:

We all are equal.

The.format() method has many advantages over the placeholder method:

  • We can insert object by using index-based position:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print('{2} {1} {0}'.format('directions',
                           'the', 'Read'))

chevron_right


Output:

Read the directions.
  • We can insert object by using assigned keywords:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print('a: {a}, b: {b}, c: {c}'.format(a = 1,
                                      b = 'Two',
                                      c = 12.3))

chevron_right


Output:

a: 1, b: Two, c: 12.3
  • We can reuse the inserted objects to avoid duplication:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))

chevron_right


Output:

The first second was alright, but the second second was tough.

Float precision with the.format() method:

Syntax: {[index]:[width][.precision][type]}

The type can be used with format codes:

  • ‘d’ for integers
  • ‘f’ for floating-point numbers
  • ‘b’ for binary numbers
  • ‘o’ for octal numbers
  • ‘x’ for octal hexadecimal numbers
  • ‘s’ for string
  • ‘e’ for floating-point in an exponent format

Example:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

print('The valueof pi is: %1.5f' %3.141592)
  
# vs.
  
print('The valueof pi is: {0:1.5f}'.format(3.141592))

chevron_right


Output:

The valueof pi is: 3.14159
The valueof pi is: 3.14159

Formatted String Literals (f-strings)

This formatting style was presented in python 3.6. f-strings have some advantages over the.format method discussed above. Here we can use outside variables directly into the string instead of passing them as arguments. 

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

name = 'Ele'
  
print(f"My name is {name}.")

chevron_right


Output:

My name is Ele.

This new formatting syntax is very powerful and easy. You can also insert arbitrary Python expressions and you can even do arithmetic operations in it.

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

a = 5
  
b = 10
  
print(f"He said his age is {2 * (a + b)}.")

chevron_right


Output:

He said his age is 30.

We can also use lambda expressions in f-string formatting.

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

print(f"He said his age is {(lambda x: x*2)(3)}")

chevron_right


Output:

He said his age is 6

Float precision in the f-String method:

Syntax: {value:{width}.{precision}}

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

num = 3.14159
  
print(f"The valueof pi is: {num:{1}.{5}}")

chevron_right


Output:

The valueof pi is: 3.1416

Note: Note that with f-strings, precision refers to the total number of digits, not just those following the decimal.

Which string formatting method is the best?

f-strings are faster and better than both %-formatting and str.format(). f-strings expressions are evaluated are at runtime, and we can also embed expressions inside f-string, using a very simple and easy syntax. The expressions inside the braces are evaluated in runtime and then put together with the string part of the f-string and then the final string is returned.

Note: Use f-Strings if you are on Python 3.6+, and.format() method if you are not.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :