Python allows String formatting the same way as it is done in C. String formatting operators allow you to embed variables inside a string. This tutorial included various examples to shown how we can play with strings with the help of these amazing operators.
%c is used when you want to embed a single character. You cannot add more than one character with %c.
val = 'J' print("The name John starts with letter - %c" %val)
Download the code
Run the code
Keeping the information given above in mind can you find what is wrong with the following piece of code?
val = 'J' print("The name John starts with letter - %c" %val)
Now, that we know how to insert a single character in a string, the next logical thing to learn is how to embed a string within a string. This is achieved with the help of %s. In the following piece of code a variable val has the value of ‘Apple’. The variable val is inserted inside the string using %s.
val = 'Apple' print("A For - %s" %val)
Download the code
Run the code
%i and %d can be used to insert a signed decimal integer in the string. In the following piece of code, there are two variables val1(15) and val2(20). In the first string val1 is in inserted using %i and in the second string value is inserted using %d.
val1 = 15 val2 = 20 print("Val1 is %i" %val1) print("Val2 is %d" %val2)
Download the code
Run the code
Similarly, if you want to embed an unsigned integer use %u.
The following code inserts octal integer value with the help of %o. variable val1 has the value of 127. The vaue inserted is 177.
val1 = 127 print("Val1 is %o" %val1)
Download the code
Run the code
both %x and %X are used to insert hexadecimal integer value. The only difference is that one inserts value is lower case letters and the other inserts values in uppercase letters. Try the following code and observe the difference.
val1 = 127 print("Val1 in lower case is %x" %val1) print("Val1 in upper case is %X" %val1)
Download the code
Run the code
Both %e and %E are used to insert exponential value. The only difference is that one inserts value is lower case letters and the other inserts values in uppercase letters. Try the following code and observe the difference.
val1 = 127 print("Val1 exponential value in lower case is %e" %val1) print("Val1 in upper case is %E" %val1)
Download the code
Run the code
If you want to insert a floating point real number in a string use %f.
val1 = 127 print("Val1 floating point value is %f" %val1)