String formatting in Python
In this article, we will discuss how to format string Python.
String formatting
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 in Python:
- Formatting with % Operator.
- Formatting with format() string method.
- Formatting with string literals, called f-strings.
- Formatting with String Template Class
- Formatting with center() string method.
So we will see the entirety of the above-mentioned ways, and we will also focus on which string formatting strategy is the best.
Method 1: 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 1: Formatting string using % operator
Python3
print ( "The mangy, scrawny stray dog %s gobbled down" % 'hurriedly' + "the grain-free, organic dog food." ) |
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 2: Injecting multiple strings using % operator
Python3
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 3:
Python3
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
Python3
print ( 'The value of pi is: %5.4f' % ( 3.141592 )) |
Output:
The value of pi is: 3.1416
Example 2:
Python3
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
Python3
variable = 12 string = "Variable as integer = % d \n\ Variable as float = % f" % (variable, variable) print (string) |
Variable as integer = 12 Variable as float = 12.000000
Note: To know more about %-formatting, refer to String Formatting in Python using %
Method 2: 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
Python3
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:
Python3
print ( '{2} {1} {0}' . format ( 'directions' , 'the' , 'Read' )) |
Output:
Read the directions.
- We can insert objects by using assigned keywords:
Python3
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:
Python3
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:
Python3
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
Method 3: 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
Python3
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
Python3
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
Python3
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
Python3
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
Method 4: 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
Python3
# 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)) |
Output:
Hello ! This is GeeksforGeeks.
Note: To know more about String Template class, refer to String Template Class in Python
Method 4: String center() method
The center() method is a built-in method in Python’s str class that returns a new string that is centered within a string of a specified width.
Example: Formatting string using center() method
Python3
string = "GeeksForGeeks!" width = 30 centered_string = string.center(width) print (centered_string) |
GeeksForGeeks!
String formatting: % vs. .format vs. f-string literal
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.
Please Login to comment...