Python String Formatting : Home Business Concepts
Sign up for PayPal and start accepting credit card payments instantly.

Python String Formatting

Posted by Linda | 8:45 AM

In the last couple of projects at work, my focus has really been on using Python more rather than the usual Java that most of our work is written in. I have been developing in Java for the past 6 year, and have recently thought about taking on a project that didn't require Java at all.

The idea came after I read the seven languages in seven weeks - if you haven't seen the book, I would suggest you pick up a copy. It's a great resource for someone like myself whose whole development life was based on Java. Worth every penny.

So, one of the few gotchas you come across when you start working with Python is indentation error - this happens quite often if you are not using an IDE that indents the code for you. Unlike other languages, Python explicitly enforces the use of indentation. It trips up many beginners and not easy to spot.

Another thing I find fascinating is the string formatting - I have used

"%s %d" % (var,num)
"{0} {1}".format(var,num)
 ...but wondering which of the two folks prefer.
The .format() version seems much easier to understand, more elegant to work with, but it is not backward compartable. If you have Python 2.6 of below, the first one would be better. Python 3 and above support the format() version which means that if you are running Python 3, you should not be using anything other than the format().

I prefer the format() version, but the problem we have now is that our version at work is still Python 2.6; so no one is looking to upgrade. With half of the developers working on different projects, I think this might be the right time to ask if we could upgrade.

Related Posts Plugin for WordPress, Blogger...