tags:

views:

199

answers:

3

i want get a string from a list

thanks

+18  A: 
''.join(map(str, [1,2,3,4] ))
  • map(str, array) is equivalent to [str(x) for x in array], so map(str, [1,2,3,4]) returns ['1', '2', '3', '4'].
  • s.join(a) concatenates all items in the sequence a by the string s, for example,

    >>> ','.join(['foo', 'bar', '', 'baz'])
    'foo,bar,,baz'
    

    Note that .join can only join string sequences. It won't call str automatically.

    >>> ''.join([1,2,3,4])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: sequence item 0: expected string, int found
    

    Therefore we need to first map all items into strings first.

KennyTM
good call sir... I would have overlooked that the numbers weren't strings ;)
Mark
+8  A: 
''.join(str(i) for i in [1,2,3,4])
Satoru.Logic
+3  A: 

You can use the str.join() function.

''.join(map(str,[1,2,3,4])) is the easiest way to get '1234' from [1,2,3,4]. If you wish to have another separator just change the string you call join on (ex: ' '.join(map(str,[1,2,3,4])) separates the elements of your list with a space).

Opera