[Level 1] Python int array join.
When you have a int array and you want to concatenate them into a string.
You might use this syntax, and python return you the TypeError.
>>> a=[1,2,3]
>>> print ' '.join(a)
Traceback (most recent call last):
File "", line 1, in ?
TypeError: sequence item 0: expected string, int found
How could we solve this problem?
1. Use a generator expression:
>>> print ' '.join(str(i) for i in a)
1 2 3
>>>
2. Use imap method from itertools
>>> from itertools import imap
>>> print ' '.join(imap(str, a))
1 2 3
>>>
Wish this helps.
regards,
Stanley Huang
You might use this syntax, and python return you the TypeError.
>>> a=[1,2,3]
>>> print ' '.join(a)
Traceback (most recent call last):
File "
TypeError: sequence item 0: expected string, int found
How could we solve this problem?
1. Use a generator expression:
>>> print ' '.join(str(i) for i in a)
1 2 3
>>>
2. Use imap method from itertools
>>> from itertools import imap
>>> print ' '.join(imap(str, a))
1 2 3
>>>
Wish this helps.
regards,
Stanley Huang
Comments
Post a Comment