String formatting is a method to insert a variable or another string into a predefined string. Whenever we need to insert a user input to a string, we can use string formatting. In this article, we will implement string formatting in python and will understand it using different examples.
What is string formatting in python?
String formatting is the procedure to insert a variable value into a string to enable the programmer to add new values to strings without the need to perform string concatenation.
If a user is giving his age as input and the program needs to print the sentence “User is x years old.” where x is the age of the user given as input. In this case, to print the output sentence, we use string concatenation as follows.
myInput = input("Input your age:")
try:
age = int(myInput)
print("User is "+str(age)+" years old.")
except:
print("Input is not in correct format")
Output:
Input your age:12
User is 12 years old.
The above program can be implemented to give the same result without using string concatenation by using string formatting.
How to perform string formatting?
To perform string formatting in python, we use the format() method.
First, we put some placeholders using curly braces {} in the string where we want to place the input variables. When the format() method is invoked on the string containing the placeholders, it takes input arguments which are equal to the number of placeholders in the string and places the inputs at the position of placeholders in a serial manner.
myInput = input("Input your age:")
try:
age = int(myInput)
print("User is {} years old.".format(age))
except:
print("Input is not in correct format")
Output:
Input your age:12
User is 12 years old.
We can also give multiple arguments to the format() method. When multiple arguments are passed as input to the method, it replaces the placeholders with the corresponding arguments.
For example, suppose that the user gives his/her name and age as input to the program and we have to print a sentence “User y is x years old.” where y is the name of the user and x is the age of the user. We will do it as follows.
myName=input("Input your name:")
myInput = input("Input your age:")
try:
age = int(myInput)
print("User {} is {} years old.".format(myName, age))
except:
print("Input is not in correct format")
Output:
Input your name:Aditya
Input your age:22
User Aditya is 22 years old.
We can also assign indices to the placeholders. By assigning indices to placeholders, we can provide the input arguments in a certain order and the braces at corresponding indices will be replaced by the input arguments.
In this method, the inputs are not mapped to the placeholders serially. They are mapped according to the indices. This can be understood from the following program.
myName=input("Input your name:")
myInput = input("Input your age:")
try:
age = int(myInput)
print("User {1} is {0} years old.".format(age,myName))
except:
print("Input age is not in correct format")
Output:
Input your name:Aditya
Input your age:22
User Aditya is 22 years old.
The format() method also accepts keyword arguments. To pass the inputs to the format method as keyword arguments, we first name the placeholders. Subsequently, we pass the input arguments to the method by using the placeholder names as keywords. This can be seen in the following example.
myName=input("Input your name:")
myInput = input("Input your age:")
try:
myAge = int(myInput)
print("User {name} is {age} years old.".format(age=myAge,name=myName))
except:
print("Input is not in correct format")
Output:
Input your name:Aditya
Input your age:22
User Aditya is 22 years old.
Using the placeholders and the format() method, we can also format the input floating point numbers which are used in the program as follows.
myInput = input("Input a number:")
try:
myNum = float(myInput)
print("Input number is: {:.2f}".format(myNum))
except:
print("Input is not in correct format")
Output:
Input a number:12.2345
Input number is: 12.23
Conclusion
In this article, we have looked at implementation of different types of string formatting using the format() method..We have to write the programs used in this article with exception handling using python try except to make the programs more robust and handle errors in a systematic way so that no error occurs during conversion of input from string to integer or float. Stay tuned for more informative articles.Stay tuned for more informative articles.
Yoast SEO
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.