String Formatting Operator

String Formatting Operator

Here is a table of the common string formatting operators in Python:

String Formatting Operator

				
					Operator	Description
%s	        String
%d	        Integer
%f	        Floating point
%e	        Exponential notation
%x or %X	Hexadecimal
%o	        Octal
%c	        Character
%r	        Repr (printable representation)
%i	        Integer (same as %d)
%u	        Unsigned integer (deprecated in Python 3)
%g or %G	Floating point or exponential, depending on value
%a or %A	Hexadecimal floating point
%%	        Literal % character

				
			

To use these operators, you can include them in a string along with placeholders and pass values as a tuple or dictionary to replace the placeholders with values. For example: 

				
					name = "John"
age = 25
height = 1.75
formatted_str = "My name is %s, I am %d years old, and my height is %.2f meters" % (name, age, height)
print(formatted_str)
				
			

Output:

				
					My name is John, I am 25 years old, and my height is 1.75 meters 
				
			

In the above example, %s is used as a placeholder for a string value (name), %d is used as a placeholder for an integer value (age), and %.2f is used as a placeholder for a floating point value with 2 decimal places (height). The % operator is followed by a tuple of values that are inserted into the placeholders.

Join To Get Our Newsletter
Spread the love