Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python String Format


String Format

You cannot combine strings and numbers using the plus (+) operator.

Example
print("The number is " + 10)
TypeError: can only concatenate str (not "int") to str

After running the above program, we got the type error (TypeError: can only concatenate str (not "int") to str).


Format Function

You can combine strings and numbers by using the format() function.

The format() function takes the passed arguments, formats them, and places them in the string where the placeholders {} are.

Example
print("The number is {}".format(10))
The number is 10

Here, we combined the string text and integer number using the format() function.


Format Function with Multiple Arguments

The format() method takes an unlimited number of arguments, and is placed into the respective placeholders.

Example
print("The number one is {}, the number two is {}".format(10, 20))
The number one is 10, the number two is 20

Format Function with Index Number

You can also use the index numbers in string text to set argument values from the format() function.

Example
print("The number one is {1}, the number two is {0}".format(10, 20))
The number one is 10, the number two is 20

Here in the output, you can see the number 20 is printed for the number one text, because we put the index number 1 for the number one text, and the 0 index has printed the number 10.