String formatting in Python



String formatting in Python

In this article, we will discuss how to format string Python. String formatting is the process of infusing things in the string dynamically and presenting the string. There are four different ways to perform string formatting:-

  • Formatting with % Operator.
  • Formatting with format() string method.
  • Formatting with string literals, called f-strings.
  • Formatting with String Template Class

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

 

Formatting string using % Operator

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

 

 

Example: Formatting string using % operator

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

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: Injecting multiple strings using % operator

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

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 formats, conversion methods visit the official documentation.

Example:

 

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

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: Float point precision using % operator

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

Output:

The value of pi is: 3.1416

Example 2:

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

Output:

Floating point numbers: 13

Example 3: You can use multiple format conversion types in a single print statement

variable = 12
string = "Variable as integer = %d \n\
Variable as float = %f" %(variable, variable)
print (string)

Output

Variable as integer = 12 
Variable as float = 12.000000

Note: To know more about %-formatting, refer to String Formatting in Python using %

 

Formatting string using format() method

Format() method was introduced with Python3 for handling complex string formatting more efficiently. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function.

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

Example: Formatting string using format() method

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

Output:

We all are equal.

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

  • We can insert object by using index-based position:
print('{2} {1} {0}'.format('directions',
                           'the', 'Read'))

Output:

Read the directions.
  • We can insert objects by using assigned keywords:
print('a: {a}, b: {b}, c: {c}'.format(a = 1,
                                      b = 'Two',
                                      c = 12.3))

Output:

a: 1, b: Two, c: 12.3
  • We can reuse the inserted objects to avoid duplication:
print('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))

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:

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

Output:

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

Note: To know more about str.format(), refer to format() function in Python

Formatted String using F-strings

PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler.

To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.

Example: Formatting string with F-Strings

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

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: Arithmetic operations using F-strings

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

Output:

He said his age is 30.

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

Example: Lambda Expressions using F-strings

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

Output:

He said his age is 6

Float precision in the f-String method:

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

Example: Float Precision using F-strings

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

Output:

The valueof pi is: 3.1416

Note: To know more about f-strings, refer to f-strings in Python

String Template Class

In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $$ creates a single escaped $:

Example: Formatting string using Template Class

# Python program to demonstrate
# string interpolation
from string import Template
n1 = 'Hello'
n2 = 'GeeksforGeeks'
# made a template which we used to
# pass two variable so n3 and n4
# formal and n1 and n2 actual
n = Template('$n3 ! This is $n4.')
# and pass the parameters into the
# template string.
print(n.substitute(n3=n1, n4=n2))

Note: To know more about String Template class, refer to String Template Class in Python

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.

Last Updated on December 29, 2021 by admin

Leave a Reply

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

Recommended Blogs