/  Technology   /  Python String Formatting
Python String Formatting

Python String Formatting

In order to make sure a string to be displayed in expected format, we can make use of format() method.

The format() method helps in formatting selected parts of a string.

To accomplish this add placeholders (curly brackets {}) in the text, and run the values through the format() method:

 

Example:

 

print ("{}, provides the best Python course.".format("i2tutorials"))

# using format option for a
# value stored in a variable
str = "This article is written in {}"
print (str.format("Python"))

# formatting a string using a numeric constant
print ("Hello, I am {} years old !".format(25))

 

Output:

 

Python String Formatting

 

Multiple Values

 

You can also use more values just by add values to the format() method and adding more placeholders.

 

Example:

 

my_string = "{}, is the best {} to learn {} and {}" 
print (my_string.format("i2tutorials", "guide", "Python", "Data Science"))

 

Output:

 

Python String Formatting

 

Index Numbers

 

You can even use index numbers inside the curly brackets {0} to make sure the values are placed in the correct placeholders:

 

Example:

 

print("{0} love {1}!!".format("i2tutorials",
                       "Python"))

# Reverse the index numbers with the
# parameters of the placeholders
print("{1} love {0}!!".format("i2tutorials",
                       "Python"))


print("{} offers the best course for {} and {}"
.format("i2tutorials", "Python", "Data Science"))


# Use the index numbers of the
# values to change the order that
# they appear in the string
print("{1} provides the best course for {0} and {2}"
.format("Python", "i2tutorials", "Data Science"))

 

Output:

 

Python String Formatting

 

Named Indexes

 

You can also use named indexes by giving a name inside the curly brackets and use names when you pass the parameter values.

 

Example:

 

# Keyword arguments are called
# by their keyword name
print("{gfg} provides the best course for {0} and {abc}"
.format("Python", abc="Data Science", gfg ="i2tutorials"))

 

Output:

 

Python String Formatting

 

Leave a comment