-1

say that I have this list:

alist = [2, 0, 1]

How would I make a string named "hahaha" for example equal to 201 ? Not 5 (sum). Would I need to something like "

for number in alist .....

thanks !

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
dkentre
  • 289
  • 3
  • 5
  • 10

4 Answers4

4

You can use ''.join() in conjunction with map():

>>> alist = [2, 0, 1]
>>> ''.join(map(str, alist))
'201'
arshajii
  • 127,459
  • 24
  • 238
  • 287
3

Is this what you're looking for?

hahaha = ''.join([str(num) for num in alist])
print hahaha  # '201'

To explain what's going on:

The portion [str(num) for num in alist] is called a "list comprehension" -- it's like a very condensed for-loop that transforms one list into another list. In this case, it turns [2, 0, 1] into ['2', '0', '1'].

(We could, of course, write this as a for-loop instead of as a list comprehension, but it take more lines of code, and would be a little tedious to type)

The section portion ''.join(list) takes a list of strings, and sticks them all together with the empty string as the separating character. If I were to do '+'.join([str(num) for num in alist]), the output would be '2+0+1' instead.

So, the line can be thought of as a series of transformations that slowly converts the initial list into a string.

[2, 0, 1] -> ['2', '0', '1'] -> '201'

We can also wrap this whole process into a function, like so:

def make_str(list):
    return ''.join([str(num) for num in list])

print make_str([4, 3, 2, 9])  # '4329'
print make_str([9, 0, 0, 9])  # '9009'
Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
1

What about:

>>> alist = [2, 0, 1]
>>> "".join(str(i) for i in alist)
'201'

The code inside join() method is a generator expression.

wim
  • 338,267
  • 99
  • 616
  • 750
Roman Susi
  • 4,135
  • 2
  • 32
  • 47
  • 1
    [For `str.join` a genexp is both slower and less efficient than LC.](http://stackoverflow.com/a/9061024/846892) – Ashwini Chaudhary Sep 15 '13 at 20:01
  • @AshwiniChaudhary this is useful information, but do you have some links explaining? I can test it but it would be nice to understand why is it so – Roman Pekar Sep 15 '13 at 20:03
  • @RomanPekar I've updated my comment with a link. – Ashwini Chaudhary Sep 15 '13 at 20:04
  • @Ashwini Chaudhary You are right. It's even in the docs http://docs.python.org/2/library/timeit.html#basic-examples , and I checked it for both Python2.7 and 3.2, however, generator expressions may be more efficient in other settings. – Roman Susi Sep 15 '13 at 20:08
1

The string join function needs a list of strings.

''.join([str(i) for i in alist])
Graeme Stuart
  • 5,837
  • 2
  • 26
  • 46