Python

Python String Formatting

The string Formatting is a very important task of any type of programming language. It helps the user to understand the output of the script properly. The string formatting can be done in Python in various ways, such as using ‘%’ symbol, format() method, string interpolation, etc. 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.

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 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 print() method to define that the type of the variable is a string.

#!/usr/bin/env python3
# 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.

#!/usr/bin/env python3
# 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 format() method with one positional parameter.  Here, ‘{ }’ brackets are used with format() method to print the variable, color.

#!/usr/bin/env python3
# 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, 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.

#!/usr/bin/env python3
 
# Take weight value
weight = float(input("What is your weight in kg?\n"))

# Take hieght 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.

#!/usr/bin/env python3
# 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.

#!/usr/bin/env python3

# Take a string value
str = input("What is COVID-19?\n")

# Print the output using f-String formatting
print(f'COVID-19 is a {str}!')

Output:

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.

#!/usr/bin/env python3

# Take country name
country = input("What is your country name\n")

# Take affected number
number = int(input("How many people are affected by covid-19 in your country?\n"))

# Print the formatted output
print(f'{number} people are affected by coronavirus in {country}')

Output:

The output is shown on the right side of the image.

Conclusion:

Four types of sting formatting ways of Python are explained in this article. The new python programmers will be able to perform string formatting related tasks easily after reading this article.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.