This post originated from an RSS feed registered with Python Buzz
by Thomas Guest.
Original Post: Seamless sequence output in Python 3.0
Feed Title: Word Aligned: Category Python
Feed URL: http://feeds.feedburner.com/WordAlignedCategoryPython
Feed Description: Dynamic languages in general. Python in particular. The adventures of a space sensitive programmer.
We all know how to join things up for output in Python 2.6.
>>> words = ['a', 'list', 'of', 'words']
>>> numbers = 1, 2, 3, 4, 5
>>> print ' '.join(words)
a list of words
>>> print ' + '.join(str(n) for n in numbers)
1 + 2 + 3 + 4 + 5
String.join does the joining (without any unwanted extra spaces). I often create a bound method, which I think looks a little better:
>>> spaced = ' '.join
>>> concat = ''.join
>>> spaced(words)
'a list of words'
>>> concat(words)
'alistofwords'
String.join() hasn’t changed in Python 3.0, but print has.
print statement, 2.6
print ' '.join(words)
print ' + '.join(str(n) for n in numbers)
Applying the 2to3 converter to the snippet above gives
print function, 3.0
print(' '.join(words))
print(' + '.join(str(n) for n in numbers))
Alternatively, we can dispense with the explicit string.join. With some argument unpacking, Python 3.0’s new print function can do it all for us. It also stringifies the printed arguments, so we don’t need the str(n)’s either.
look no joins
print(*words)
print(*numbers, sep=' + ')
Sys.stdout is the defaulted destination for the print calls above. Supply a file (or anything with a write(string) method) to print elsewhere.
If you’re using Python 2.6 but would like to use Python 3.0 style printing, use a future statement.