Menu Close

Python String format() Method

Python string format() method

In this article, you will learn about the Python string format() method. Python string format function is used to work with string. The string format function is the best function when you want to insert variable value inside a string.

In previous tutorial we have seen all about Python string find() method.

Python String format() Method:

In Python, the string format() method is a built-in string method. Python string format() method is used to format the specified values and insert them inside strings placeholder.
To use the format() method in python string we need to use curly braces ( {} ). If you have more than one variable then we use assign numbers in curly braces.

Syntax:

The syntax of Python string format function is:

string.format(value1, value2,...)

Parameter:

value1, value2,.. – Required. One or more value that should be formatted or inserted inside the string.

Return Type:

The string format() method return formatted string.

The Placeholders:

The placeholders can be identify by named index {age}, index number {1} or empty placeholder {}.

Example:

print("My name is {name} and I am {age} years old.".format(name = 'Vishvajit Rao', age = 22))
print("My name is {0} and I am {1} years old.".format('John',24))
print("My name is {} and I am {} years old.".format('Harry',26))

Output

My name is Vishvajit Rao and I am 22 years old.
My name is John and I am 24 years old.
My name is Harry and I am 26 years old.

Let’s see an example for using Python format() string method.

Python string format() method example:

Here we will take various example of string format function, so that you can understand string format method in better way.

Example 1:

str = "Programming Funda"
print("Welcome to the {}.".format(str))

#More than one variable.
str1 = "Programming Funda"
str2 = "Python"

print("Welcome to the {0} and it is {1} tutorial.".format(str1, str2))

Output

Welcome to the Programming Funda.
Welcome to the Programming Funda and it is Python tutorial.

Example 2:

# Variable declaration  
val = 10  
# Calling function  
print("decimal: {0:d}".format(val)); # display decimal result  
print("hex: {0:x}".format(val));     # display hexadecimal result  
print("octal: {0:o}".format(val));   # display octal result  
print("binary: {0:b}".format(val));  # display binary result  

Output

decimal: 10
hex: a
octal: 12
binary: 1010

Conclusion:

In this article, you have learned all about Python string format() method to format the string.
If you have collection of variables and you want to insert them inside string, Then you can go with string format function.

I hope this tutorial will help you. If you like this article, please comment and share with your friends who want to learn Python programming.

Fore More Information:- Click Here

Python String find() Method
Python String index() Method

Related Posts