Monday, April 27, 2009

Python Format Specifier for Strings

When you are coding in python you can make use of the Format Specifier for Strings to format the output. In basic it is very simple to use when you like to manipulate your output. For example if we want to make "Your name is; Johan" we can do a print command as seen in the previous post however we can also do it a little different.

we can do a print "your name is: %s" % ("Johan") as seen in the example below

this will give us some more freedom in formating we now can for example manipulate the position of the first string which is represented by %s by adding a 10 between the % and the s which will make sure that there is space for a word of 10 characters. However he name Johan is 5 characters wide so it will leave space for 5 more characters.

you can also play around with adding a + or a - in front of the 10 so it will read +10 or -10. Just try it out and have some fun finding out how it works in detail.

No comments: