Pages

Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, October 27, 2011

Python string formatting: % vs. .format


Python 2.6 introduced the string.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations?

The following uses each method and has the same outcome, so what is the difference?

#!/usr/bin/python
sub1 = "python string!"
sub2 = "an arg"


a = "i am a %s"%sub1
b = "i am a {0}".format(sub1)


c = "with %(kwarg)s!"%{'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)


print a
print b
print c
print d

To answer the question... .format just seems more sophisticated in many ways. You can do stuff like re-use arguments, which you can't do with %. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

"hi there %s" % name


yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

"hi there %s" % (name,)   # supply the single argument as a single-item tuple


which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.

Why would you not use it?

  • not knowing about it (me before reading this)
  • having to be compatible with Python 2.5


Tuesday, August 9, 2011

Convert Windows-1251 (Cyrillic) to Unicode using Python

Just 4 lines of code to convert some file content from Windows-1251 (Cyrillic) to Unicode with Python

import codecs

f = codecs.open(filename, 'r', 'cp1251')
u = f.read()   # now the contents have been transformed to a Unicode string
out = codecs.open(output, 'w', 'utf-8')
out.write(u)   # and now the contents have been output as UTF-8