Jump to content

Python String Formatting


Linux Hint

Recommended Posts

String formatting is a significant feature of any programming language. By using string formatting, you can properly arrange your string. String formatting helps users understand the output in a well-defined, coherent way. In Python, string formatting can be performed in various ways, i.e., by using the ‘%’ operator and the ‘format ()’ function.

This article explains string formatting in Python using the ‘%’ operator and the ‘format ()’ function. The Spyder3 editor is used to write and run the Python scripts shown in this article.

Format String Using the % Operator

String formatting using the ‘%’ operator is the oldest C-style string formatting function. You can declare multiple variables in Python and format them by using the ‘%’ operator. Multiple argument specifiers are used with the % operator.

The following include basic argument specifiers that are used with the ‘%’ operator:

  1. %s – Used with a string or with any string representation, like a list.
  2. %d – Used for integers.
  3. %f – Used for floating-point numbers.
  4. %x – Used with hex representation.

Print String Using %s

Let us now create a Python script and use argument specifiers for string formatting.

We have a variable name that contains the value of the user name. %s is used inside the print function as an argument specifier because the type of name variable is a string.

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#print greeting to the user
name = "Mark"
print ("Hello %s. Welcome to the LinuxHint" %name)

Output

The output is displayed in the Python console.

word-image-228.png

Print Integer Using %d

Print the price of the shirt by using the %d argument specifier. The price value is an integer.

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#print price of the shirt
price = 100
print ("The price of the shirt is $%d."% price)

Output

The output is displayed in the Python console.

word-image-229.png

Print Floating-Point Number Using %f

Similarly, we can print the price of the shirt using the %f argument specifier. This time, the price value is float.

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#print price of the shirt
price = 10.99
print ("The price of the shirt is $%f."% price)

Output

The output is displayed in the Python console.

word-image-230.png

Multiple Argument Specifiers for Formatting Multiple String Data

To format multiple strings, multiple specifiers are used. Parentheses [()] are used to define the multiple specifiers.

Here, we will print the name and age of a person using a multiple argument specifier.

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#print name and age
#intialize name and age variables.
name = "Kamran"
age = 25
print ("My name is %s and my age is %d." %(name,age))

Output

The output is displayed in Python console.

word-image-231.png

Let us now print the name and profession of a person by using the multiple argument specifier and format the multiple string data.

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#print name and age
#intialize name and age variables.
name = "Kamran"
profession = "Software Engineer"
print ("My name is %s and I am a %s." %(name,profession))

Output

The output is displayed in the Python console.

word-image-232.png

You can also take the name and profession as an input from the user, as follows:

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#print name and age
#initialize name and age variables.
name = input("What is your name?\n")
profession = input("What is your profession?\n")
print ("\nMy name is %s and I am a %s." %(name,profession))

Output

The output is displayed in the Python console.

word-image-233.png

You can print an object that is not a string using the %s argument specifier. Here, we are printing a list using %s:

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#Initialize the list
person_list = [1,"Mark",2,"John",3,"Taylor"]
print("A list: %s" % person_list)

Output

The output is displayed in the Python console.

word-image-234.png

String Formatting with format () Function

Using the ‘%’ operator for string formatting is the old method. Python 3 introduced a new function for string formatting. You can easily format a string by calling the format () function on any type of string object. The format () function was later incorporated in Python 2.7, as well.

In Python, we use positional and keyword parameters for string formatting. Positional parameters are accessed through the index values, as array values are accessed using an index. Keyword parameters are accessed with a particular keyword. We will see the use of positional and keyword parameters with the format () function.

format () Function Demonstration

In the example given below, we use the format () function to format the string. The [{}] brackets are used to print the value of the string variable. These brackets are placeholders used to define the positional and keyword parameters. In this example, the brackets will be replaced with the word “Example.”

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#Store value in a string variable str
str = "This is an {}"
#using format function to print the value
print(str.format("Example"))

Output

The output is displayed in the Python console.

word-image-235.png

String Formatting Using Multiple Placeholders

Now, we will use multiple placeholders [{}{}] for string formatting. In this example, we will use two placeholders: the first placeholder is for “LinuxHint,” and the second placeholder is for “web based.”

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#Store value in a string variable str
str = "{} is a {} platform for linux related material."
#using format function to print the value
print(str.format("LinuxHint","web based"))

Output

The output is displayed in the Python console.

word-image-236.png

String Formatting Using Positional Parameters

Positional parameters are accessed by the index values. The index values always start from zero. In this example, we will use two positional parameters, i.e., name and age. We will take the name and age from a user as the input and then print the output using the format () function. The index for name is 0 and the index for age is 1.

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#Store value in a string variables
name= input("Enter your name\n")
age=input("\nEnter your age\n")
#using format function to print the value
print("My name is {0} and my age is {1}".format(name,age))

Output

The output is displayed in the console.

word-image-237.png

You can use as many positional parameters as you want. If we extend the previous example, we can add profession and residence city of the user. The index values for the profession and residence city will be 2 and 3, respectively.

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#Store value in a string variables
name= input("Enter your name\n")
age=input("\nEnter your age\n")
profession= input("Enter your profession\n")
city= input("Enter your residence city\n")
#using format function to print the value
print("My name is {0} and my age is {1}.I am {2} by profession and lives in
{3}"
.format(name,age,profession,city))

Output

The output is displayed in the Python console.

word-image-238.png

String Formatting Using Keyword Parameters

You can print the name, age, profession, and residence city of the user using the keyword parameters. When using the keyword parameters, you write the keyword instead of the indexes. In the given example, name is the keyword for the user name, age is the keyword for user age, and profession and city are the keywords for the user profession and user city, respectively. The user will input the name, age, profession, and city. In the formatted function, the value of the keyword name is equal to the name variable value. Similarly, the values of the age, profession, and city keywords are equal to their respective variables.

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
#Store value in a string variables
name= input("Enter your name\n")
age=input("Enter your age\n")
profession= input("Enter your profession\n")
city= input("Enter your residence city\n")
#using format function to print the value
print("My name is {name} and my age is {age}.I am {profession} by profession and lives in
{city}"
.format(name=name,age=age,profession=profession,city=city))

Output

The output is displayed on the right side of the Python console.

word-image-239.png

Conclusion

String formatting an important feature in any programming language. It helps the user to improve the output of the program. This article showed you two types of string formatting in Python: you can use an old C-style % operator, or you can use the format () function. The format () function was introduced in Python 3 and, later on, it became part of Python 2.7, as well. This article will help Python users to write string formatting related scripts and programs.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...