One important skill in Python programming is the use of formatting strings. Here’s a little snippet to assist – but mainly to remind me in a handy place where I won’t forget it.
This post, I must admit, is mainly for my benefit. I am in the progress of teaching myself Python (version 2), and I’m currently looking at formatting strings. I have seen different operators such as ‘%s’ and ‘%d’ but have not seen a simple table / explanation on what the different string operators are and in what context to use them. The info also took me ages to find too!
A very simple example of string formatting is shown below:
print “My name is %s and my age is %d years!” % (‘Tom’, 23)
Here are the various options available with the % output string. I hope it assists you also.
Format Symbol | Conversion |
---|---|
%c | character |
%s | string conversion via str() prior to formatting |
%i | signed decimal integer |
%d | signed decimal integer |
%u | unsigned decimal integer |
%o | octal integer |
%x | hexadecimal integer (lowercase letters) |
%X | hexadecimal integer (UPPERcase letters) |
%e | exponential notation (with lowercase 'e') |
%E | exponential notation (with UPPERcase 'E') |
%f | floating point real number |
%g | the shorter of %f and %e |
%G | the shorter of %f and %E |