The Artima Developer Community
Sponsored Link

Python Buzz Forum
Seamless sequence output in Python 3.0

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Thomas Guest

Posts: 236
Nickname: tag
Registered: Nov, 2004

Thomas Guest likes dynamic languages.
Seamless sequence output in Python 3.0 Posted: Jan 10, 2009 5:10 AM
Reply to this message Reply

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.
Latest Python Buzz Posts
Latest Python Buzz Posts by Thomas Guest
Latest Posts From Word Aligned: Category Python

Advertisement

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.

no joins in 2.6 either
>>> from __future__ import print_function
>>> print(*[1, 2, 3, 4, 5], sep=' + ')
1 + 2 + 3 + 4 + 5
>>> print(1, 2, 3, 4, 5, sep=' + ')
1 + 2 + 3 + 4 + 5

Read: Seamless sequence output in Python 3.0

Topic: Steganography made simple Previous Topic   Next Topic Topic: IPython

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use