This article shows how the string data can be formatted in Python by using different string formatting methods. Spyder3 editor is used here to write and run the script.
Formatting Parameters
Two types of formatting parameters can be used in Python. These are positional parameters and keyword parameters. The parameter which is accessed by the index is called the positional parameter and the parameter which is accessed by the key is called the keyword parameter. The uses of these parameters are shown in the next part of this article.
Format Using ‘%’ Symbol
This is the oldest method of formatting string data in Python. It works like the formatting used in C language. It uses the positional parameter to format data. Some examples of this method are shown below.
Formatting Single String Data
Create a Python file with the following script. A string value is taken from the user and assigned to the variable, name. The value of the variable is printed by using the ‘%’ symbol. ‘%s’ is used in the print() method to define that the type of the variable is a string.
# Take string data from user
name=input("What is your name?\n")
# Print the formatted output using '%'
print("My name is %s" % name)
Output:
The output is shown on the right side of the image.
Formatting Multiple String Data
Using ‘()’ is not essential to print the formatted output of a single string variable when using the ‘%’ symbol. But if you want to format two or more strings using ‘%’ then use ‘()’ to define the group of string values. Create a Python file with the following script to print the formatted output of two string variables.
# Initialize two string variables
employee = "John"
profession = "Programmer"
# Print the formatted values of the variables
print("%s is a %s" % (employee,profession))
Output:
The output is shown on the right side of the image.
Format Using format() Method
This method can take both positional and keyword parameters as arguments. It can read multiple arguments and returns the formatted output of the string data. The curly brackets ({}) are used to define positional or keyword parameters in the format() method.
Syntax:
string.format( p1, p2, …, k1, k2, …)
Here, p1, p2, etc. are positional parameters, and k1, k2, etc. are keyword parameters. Some examples of using the format() method are shown below.
String Formatting Using a Single Positional Parameter
If you don’t define the value of the positional parameter when using the format() method then the value will start from 0. Create a Python file with the following script to know the use of the format() method with one positional parameter. Here, ‘{ }’ brackets are used with the format() method to print the variable, color.
# Take string data from the user
color=input("What is your favorite color?\n")
# Print the formatted output using single parameter
print('My favorite color is {}'.format(color))
Output:
The output is shown on the right side of the image.
String Formatting Using Multiple Positional Parameters
Create a Python file with the following script to know the use of multiple positional parameters with positional values in format() method.
Here, two input values will be taken from the user and assigned to the variables named weight and height.
Next, the BMI value will calculate based on weight and height values. format() method is used in the script to print these three values using positional parameters.
# Take weight value
weight = float(input("What is your weight in kg?\n"))
# Take height value
height = float(input("What is your height in meter?\n"))
# Calculate BMI value based on height and weight
BMI=round((weight/(height*height)),2)
# Print the formatted output using multiple parameters
print('Your height is {1} and weight is {0}\nYour BMI is:{2}'.format(weight,height,str(BMI)))
Output:
The output is shown on the right side of the image. Here, height value is given in meter and weight value is given in kg to calculate BMI value.
String Formatting Using the Keyword Parameter
Create a Python file with the following script to see the use of the keyword parameter in the format() method. When ‘if’ condition is true then two keyword parameters named ‘name’ and ‘grade’ are used otherwise one keyword parameter named ‘grade’ is used to set the value.
# Take ID value as input
id = input("Enter your ID:\n")
# Define function to get grade value
def result(id):
switcher={
"1001":"A+",
"1002":"B+",
"1004":"C+"
}
return switcher.get(id,"Invalid")
# Check the grade value
if(result(id) != "Invalid"):
# name are grade are keyword parameters
print('{name} got {grade}'.format(name=id,grade=result(id)))
else:
# One positinal parameter and another keyword parameter
print('{0} got {grade}'.format(id,grade="F"))
Output:
The output is shown on the right side of the image. Here, ‘1001’ is taken as input for the first time that exists in ‘switcher’. ‘1003’ is taken as input for the second time that doesn’t exist in ‘switcher’ and that value of grade is set to ‘F’.
Format using String Interpolation
String interpolation or f-Strings is a new feature of python 3.6. Python expression can be added within a string constant to create formatted string data. The character, ‘f’ is used as a prefix with the string constant to format the string. Some examples of using f-String are shown below.
Format simple Variable Using f-Strings
Create a Python file with the following script to know the use of f-String in string formatting. Here, ‘{}’ is used with the string variable in the print() method.
# Take a string value
str = input("What is Python?\n")
# Print the output using f-String formatting
print(f'Python is a {str}!')
Output:
The output is shown on the right side of the image.
Format Multiple Variables Using f-String
Create a Python file with the following script to know the use of multiple variables in f-String. Here, two inputs will be taken from the user and printed using f-String.
# Take country name
country = input("What is your country name\n")
# Take affected number
capital = input("What is the capital name of your country?\n")
# Print the formatted output
print(f'The capital of {country} is {capital}')
Output:
The output is shown on the right side of the image.
Conclusion
Four types of string formatting ways of Python are explained in this article. The new Python programmers will be able to perform string formatting tasks easily after reading this article.