[Q] A better way to print?
Dan Schmidt
dfan at dfan.org
Sun Feb 23 19:46:44 EST 2003
eRrEiMcOgVoErMrE at cox.net (Eric Gorr) writes:
| Dan Schmidt <dfan at dfan.org> wrote:
|
|| eRrEiMcOgVoErMrE at cox.net (Eric Gorr) writes:
||
|| | I have some print code that looks like:
|| |
|| | for i in range(N-1):
|| | print W[i],
|| | sys.stdout.softspace = 0
|| | print '-',
|| | sys.stdout.softspace = 0
|| | print W[-1]
||
|| In this case,
||
|| print '-'.join(W)
|
| hummm.
|
| Got the following error:
|
| Traceback (most recent call last):
| File "beatpath.py", line 62, in ?
| print '-'.join(W)
| TypeError: sequence item 0: expected string, int found
Oh, I guess join() expects the list it's joining to be all strings
already. I didn't know what was in W.
Maybe this is starting to get obscure, but
print '-'.join( [ str(x) for x in W ] )
or
print '-'.join( map (str, W ) )
both work.
The first says "Use '-' to join a list that contains a string
representation of x for every x in W." The [ a for b in c ] syntax is
called a list comprehension.
The second says "Use '-' to join a list that is generated by applying
the str() function to every element of W", where str() turns things
into strings.
They do exactly the same thing, so use whichever feels more natural.
Dan
--
http://www.dfan.org
More information about the Python-list
mailing list