Python V2 String Formatting

python-operator-snippet

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
%sstring conversion via str() prior to formatting
%isigned decimal integer
%dsigned decimal integer
%uunsigned decimal integer
%ooctal integer
%xhexadecimal integer (lowercase letters)
%Xhexadecimal integer (UPPERcase letters)
%eexponential notation (with lowercase 'e')
%Eexponential notation (with UPPERcase 'E')
%ffloating point real number
%gthe shorter of %f and %e
%Gthe shorter of %f and %E
Tags: , ,
Previous Post

Google Chrome Search Engine

Next Post

Fixwin – fix windows annoyances

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.