How To Format String In Python
In this tutorial, we’ll learn how to easily format string in Python. We’ll going through multiple methods and examples to understand how to practically format string in Python.
Introduction: Format String In Python
It specifies adding new data dynamically in a string with proper formats. Let’s discuss about the multiple methods which can be used to format string in Python.
3 Ways To Format String In Python
Let’s discuss about 3 different ways for string formatting in Python programming language. These are listed below:
- % Operator
- Python String format() Method
- f-String
Method 1: % Operator
This symbol % is also known as ‘string formatting operator’. Its an old method to format a Python string. See below example:
print('This is %s Programming' %'Python')Get Zeeshan Ali’s stories in your inbox
Join Medium for free to get updates from this writer.
Output
This is Python ProgrammingWe’ve specified a string ‘Python’ and have used it inside the main string using %s.
- %s is for strings
- %d is for integers
- %f is for floating point values
- %b is for binary format
We can also inject multiple values. See below examples:
print('This is %s Programming %s' %('Python','Language'))
print('This is %s Programming %d' %('Python',3))
print('This is %s %d %s' %('Python',3,'Programming'))
print('This is Python Programming %d' %3)
print('This is %s Programming %f' %('Python',3.0))
name='Python'
print('This is %s %d' %(name,3))Output
This is Python Programming Language
This is Python Programming 3
This is Python 3 Programming
This is Python Programming 3
This is Python Programming 3.000000
This is Python 3Method 2: Python String format Method
This method can be used to inject data specified in it into main string using placeholders. These placeholders are specified using curly braces {}. See below examples: Continue reading…



