How do I convert a list of int
s to a single string, such that:
[1, 2, 3, 4]
becomes '1234'
[10, 11, 12, 13]
becomes '10111213'
... etc...
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") .
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.
In Python, you can get the length of a string str (= number of characters) with the built-in function len() .
''.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With