-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
  • 232,417
  • 55
  • 437
  • 487
dkentre
  • 267
  • 3
  • 5
  • 9

4 Answers4

4

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

>>> alist = [2, 0, 1]
>>> ''.join(map(str, alist))
'201'
arshajii
  • 123,543
  • 24
  • 232
  • 276
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
  • 49,608
  • 27
  • 153
  • 207
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
  • 302,178
  • 90
  • 548
  • 690
Roman Susi
  • 3,889
  • 2
  • 30
  • 41
1

The string join function needs a list of strings.

''.join([str(i) for i in alist])
Graeme Stuart
  • 5,277
  • 1
  • 23
  • 43