String Formatting in Python
In this article we discussed different techniques of string formatting in python like modulo operator, built-in format and f-string.
Introduction
In this article, we will discuss string formatting in Python.
Python handles textual data with str objects, more commonly known as strings.
In Python, a string is an immutable sequence of Unicode code points.
Strings are one of the most used and essential data types in Python. With that said, proper text formatting makes code and data much easier to read and understand. There are a bunch of ways to achieve string formatting in Python.
Let’s check them out!
Best-suited Python for data science courses for you
Learn Python for data science with these high-rated online courses
Table of Content
Formatting Strings in Python
Any time you have to program something that has to be human-readable, you are very likely to encounter instances where you will need to perform string formatting. Fortunately, Python offers a different approach that you can use to format strings.
The most commonly used ones are:
- Using modulo (%) operator
- Python’s built-in format() method
- Python f-strings
Great, let’s dig in!
String Formatting Using modulo (%) Operator
Using the modulo (%) operator is considered to be the “old way” of formatting strings. This formatting technique has been there since Python’s inception and loosely based on printf statement of C language.
Python provides the binary operator %, which can be applied on strings to format them in a very simple manner. % operator provides a compact way to code multiple string substitutions at once rather than doing it in parts.
Let’s look at that with the help of an example.
#Example 1: string formatting using % operator print("%s is %d of the best programming languages" % ('Python', 1))
Not making sense? No problem!! String formatting examples might look a little strange until you understand the syntax or what is actually being done there.
To format strings using % operator:
- On the left side of the % operator, you need to provide a format string containing one or more conversion targets, each of which starts with %
- On the right, you need to provide a Python object that you want Python to insert in the format string on the left in the place of conversion targets
For instance, in the above example, we have %s and %d as our conversion targets to the left of the % operator and to the right of the % operator we have the string ‘Python’ that replaces %s, the number 1 that replaces %d.
For advanced string formatting using %, you can the format given below:
%[(keyname)][flags][.precision]typecode
Between the % and the typecode (i.e f, e, g, x, etc.) you can do any of the following:
- Give a keyname for indexing the dictionary (if used on right side of expression)
- List flags to specify things like + and – for positive and negative numbers, 0 to add 0 padding, – for left justification, etc.
- Set the decimal point precision for floating point numbers
Let us master this with help of few examples:
#Example 2: Using % operator #Passing the values directly to the % operator print("%d %s %s %0.1f" % (1, 'use', 'Python', 3.0 )) #Type-specific substitutions print('%s -- %s -- %s' % (3.14159, [1.0, 2, 3], .3)) #All types match a %s conversion target #Using keywords to pass values x = 1.2345 print('%e | .2f | %+g' % (x, x, x)) #Passing a dictionary directly to the % operator dict1 = {'language': 'Python', 'version': 3.7} print("I use %(language)s programming language and the version is %(language)s %(version)0.1f" % dict1)
You can learn more about this printf style string formatting in the official Python Documentation.
String Formatting Using format() Method
Python 3.0 introduced a new way of string formatting that provided a large degree of flexibility and customization compared to C printf style formatting: format() method.
str.format()
It can be used to perform string formatting operations.
It’s more like a normal function call rather than an expression.
The format string contains substitution targets (replacement fields) and arguments to be inserted either by position (e.g., {2}) or keyword (e.g., {sam}).
Just like you would pass arguments to functions and methods by position or keyword.
Here’s an example to clear the picture.
#String formatting using string format() method str1 = "I" str2 = "Love" str3 = "Python" #passing argument by position print('{0} {1}, {0} {2}'.format("Python", 2.0, 3.0)) #passing by relative postion print('{} {} and {}'.format("I", "Love", "Python")) #passing by keyword name print('{str1} {str2} code using {str3}'.format(str1 = "I", str2 = "Love", str3 = "Python")) #both position & keyword print("{0} version {ver}".format("Python", ver = [2.0, 3.7]))
Let’s consider another example.
#More about string formatting using format() str3 = "Python" template = '{0} {1} {2}' # By position print(template.format('I', 'Love', str3)) print('{0:f}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, 3.14159)) X = '{0}:{ver}'.format(str3, ver=[2.0, 3.0]) print(X) tuple1 = (334, 45, 23456, 103, 66) print('{0} {2} {1} {2} {3} {2} {1} {2}'.format(*tuple1)) #Alignment & padding print('{:~^30s}'.format('Python')) print('{:~>30}'.format('Python')) print('{:0=8d}'.format(-1234))
The points that we can infer from the example above are as follows:
- You can pass arguments either by position or keyword name, or both as shown above
- format() methods creates and returns a new string object, which you can print or save for further use
- You can use the format method just like % operator by adding extra syntax in the format string.
example:
'{0:f}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, 3.14159)
- Unlike %, format allows repetition of arguments as shown in the above example,
'{0} {2} {1} {2} {3} {2} {1} {2}'.format(*tuple1)
- Note that, you can use pass dictionary keys, tuples, lists, and other objects as arguments to format method
- The format method also allows you to change the alignment of the string using the syntax :[fill_char][align_operator][width]. The align_operator can be:
- <, for left-alignment within the given width
- >, for right-alignment within the given width
- ^, for center alignment
- =, to place the padding after the sign
(Refer to the last three line of the code)
Advance Usage of format() Method
You can use more complex format calls to perform more advanced string formatting.
The format strings can name dictionary keys and object attributes just like normal Python syntax.
You know, like a dictionary key inside a square bracket to fetch dictionary values and dots for object attributes of an item.
#Advanced String formattign using format() import sys #Example1 list1 = list('Naukri') print("The sample list", list1) print('first={0[0]}, third={0[2]}'.format(list1)) print('first={0}, middle={1}, last={2}'.format(list1[0], list1[2:4], list1[-1])) #Example2 print('My {1[type]} runs {0.platform}'.format(sys, {'type': 'laptop'})) print('My {map[type]} runs {OS.platform}'.format(OS=sys, map={'type': 'laptop'}))
The first example shows how you format strings and can name list (also other sequence types) offsets to perform indexing and other related operations.
The second example, fetches a dictionary value using key, and then fetches attribute “platform” from an already imported sys module using dot.
String Formatting Using f-strings
F-strings, also called “formatted string literals”, is relatively a new concept that was introduced in PEP 498 (Python3.6 and upwards).
You could say that it was this new string interpolation that was a simple and easy alternative to str.format.
F-strings are string literals that have an f (or F) prepended at the beginning of the string & expressions that are enclosed inside curly braces.
These expressions get evaluated during runtime and then are formatted using the __format__ protocol.
#Example1 msg1 = 'Hello World!' msg2 = 'Welcome to Naukri Leaarning' print(f'msg: {msg1} {msg2}')
If you check the output, you will notice that msg1, and mgs2 will be replaced by their respective values. Isn’t that simple?
You don’t have to use the% operator or format() method.
However, you should know that f-strings do not replace format() completely. There are situations where using format() would be more effective than f-strings.
But the real beauty of f-strings is that they are evaluated during runtime.
Therefore, you can easily include expressions, conditions, alignment, and formatting into your strings.
Presentation Types & Changing Alignment of Strings
When you specify a placeholder for a value in string literal, by default Python assumes that the value has to be displayed as a string, unless you specify another type.
For example,
#f-strings presentation types print(f'{3.1415926:.3f}') #floating point type using f print(f'[{20:5d}]') #integer type & alignment using d print(f'{68:c} {99:c}') #character type using c print(f'{"Python":s} {3.7:.1f}') #string type (default) using s print(" ") #alignment print(f'[{20:5d}]') #field width print(f'[{3.1415926:<10.2f}]') #left alignment using < print(f'{3.1415926:>10.5f}') #right alignment using > print(f'{"Python":^s} {3.7:^.1f}') #centering a value using ^ print(" ") #numeric formatting print(f'{-20:2d}') #inserting -ve sign print(f'{20:+10d}') #inserting +ve sign print(f'{1234567.89:,.3f}') #grouping digits
Formatting Arbitrary Expressions
Like I mentioned earlier, since f-strings are evaluated during runtime, you can put almost all sorts of expressions inside the curly braces.
Let’s see how to format these expressions.
#Formatting Arbitrary Expressions Using f-strings n = 87 print(f'Is {n} even?: {True if n%2==0 else False}') print(f'{n} * {n} is {n * n}') name = "Sheldon Cooper" profession = 'scientist' series = 'Big Bang Theory' print(f'{name.lower()} is funny.') #multiline f-strings message = ( f'Hi {name}. ' f'You are a {profession}. ' f'You are a character in {series}.' ) print(message)
More About F-strings & Best Practices
Here are few points that you should know about f-strings:
- f-strings are faster than % operator and format() method
- You can also call methods with f-strings, eg, name.lower() as shown above
- Use different types of quotation marks outside the f-string and inside the expression
- When working with dictionaries in f-string, if you are using single quotes for keys, then use double quotes for the f-strings else you might get syntax error
- Expression part of f-string should not include any comments generated using # symbol
This is just the minimum of what you can do using f-strings.
So, make sure to check official Python documentation to know more on how to do formatting using f-strings.
Which Formatting Technique Should You Use?
The next question is to decide which technique to use in string formatting in python.
You can consider these points to make the decision:
- Formatting with f-strings is faster compared to format() and %operator
- % expression cannot handle keywords, attribute references, and binary type codes
- format() method has a couple of advanced features that % expression does not
- The format() method also makes substitution value references more easy and explicit
That’s it folks! Hope you found this interesting. If you have any queries, please let us know in the comment section.
Top Trending Articles:Data Analyst Interview Questions Data Science Interview Questions Machine Learning Applications Big Data vs Machine Learning Data Scientist vs Data Analyst How to Become a Data Analyst Data Science vs. Big Data vs. Data Analytics What is Data Science What is a Data Scientist What is Data Analyst
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio