Let's say you have a list of individual characters, like this:
chars = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
What if you need to convert this list of characters into a string? In cases like this, you can use the
'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] ''.join(chars) 'hello world'chars = [
Note that the
join method on the array. This is why we use call
join on an empty string, we don't actually want the individual characters to be separated by anything.
If you want to separate the characters by something, and not just an empty string, use that character as the separator:
'0', '1', '2', '3', '4'] ','.join(chars) '0,1,2,3,4'chars = [
But what if your list of characters contains non-string objects, like integers? In that case, Python will throw an error unless you explicity convert the integers to strings.
','.join([1, 2, 3, 4]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, int found
If you have integers (or other data types) like this, first convert them to strings. This can be done in one line using the
map function, which will call a method on each item in the list and return the modified array.
Here we first show how the
map function works:
1, 2, 3, 4] map(str, integers) ['1', '2', '3', '4']integers = [
And now, putting it all together with
1, 2, 3, 4] ','.join(map(str, integers)) '0,1,2,3,4'integers = [
For another example, let's say you need to generate a template that has numbered lines for a worksheet printout. You could achieve this using
range(1,11) ')\n'.join(map(str, numbers)) + ')' '1)\n2)\n3)\n4)\n5)\n6)\n7)\n8)\n9)\n10)'numbers =
Formatted properly, the output would look like this:
1) 2) 3) 4) 5) 6) 7) 8) 9) 10)