Python - String Formatting

Python

Share
python logo

In this tutorial we will learn about string formatting in Python.

We use the % symbol in Python to format strings.

Following are the list of symbols we can use with % sign to format strings in Python.

Description Escape sequence notation
%c Character
%s String
%i Integer
%d Signed integer
%i Unsigned integer
%o Octal integer
%x Hexadecimal lower case
%X Hexadecimal upper case
%e Exponential notation with lower case e.
%E Exponential notation with upper case E.
%f Floating point numbers
%g Short for %f and %e
%G Short for %F and %E

String Formatting Example

In the following Python exercises we are formatting strings using the % operator.

Exercise #1: Insert character

In this Python program we are inserting character using %c.

# character
ch = 'A'

# string format
str = "We are inserting the following character: %c" % (ch)

# output
print(str)

We will get the following output.

We are inserting the following character: A

The character saved in variable ch is inserted in the position %c in the string str.

Exercise #2: Insert string

In this Python program we are inserting string using %s.

# string to insert
str_insert = 'World'

# string format
str = "Hello %s" % (str_insert)

# output
print(str)

We will get the following output.

Hello World

The string "World" saved in variable str_insert is inserted in the position %s in the string str.

Exercise #3: Insert integer

In this Python program we are inserting integer value using %i.

# integer
i = 10

# string format
str = "We have the following integer value %i" % (i)

# output
print(str)

We will get the following output.

We have the following integer value 10

Exercise #4: Insert floating point number

In this Python program we are inserting floating point value using %f.

# floating point number
f = 123.45

# string format
str = "We have the following floating point value %f" % (f)

# output
print(str)

We will get the following output.

We have the following floating point value 123.450000

Exercise #5: Insert octal value

In this Python program we are inserting integer value which is show as octal value using %o.

# integer
i = 12

# string format
str = "We have the following octal value %o for integer %i" % (i, i)

# output
print(str)

We will get the following output.

We have the following octal value 14 for integer 12

Exercise #6: Insert hexadecimal value

In this Python program we are inserting integer value which is show as hexadecimal value using %x (lowercase) and %X (uppercase).

# integer
i = 27

# string format
str1 = "We have the following lowercase hexadecimal value %x for integer %i" % (i, i)
str2 = "We have the following uppercase hexadecimal value %X for integer %i" % (i, i)

# output
print(str1)
print(str2)

We will get the following output.

We have the following lowercase hexadecimal value 1b for integer 27
We have the following uppercase hexadecimal value 1B for integer 27
Share