Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change [1,2,3,4] to '1234' using python

How do I convert a list of ints to a single string, such that:

[1, 2, 3, 4] becomes '1234'
[10, 11, 12, 13] becomes '10111213'

... etc...

like image 624
zjm1126 Avatar asked Apr 08 '10 06:04

zjm1126


People also ask

How do you convert numbers in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do I convert a number to a string in Python 3?

We can convert numbers to strings using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.

How do you find the number of letters in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .


1 Answers

''.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.

like image 178
kennytm Avatar answered Oct 01 '22 14:10

kennytm