How to Convert List to String with comma delimiter python with example
This post shows you an example to convert a List to a String with a comma delimiter. This also includes concatenating string lists to Single string with examples.
Python Convert List to String examples
you can convert List to String in multiple ways, One way is using String join with a delimiter such as a comma, or hyphen.
Generate Comma separated string from a List of strings in Python
The string contains a join
method that appends the iterable strings object such as list and array. This works with List of Strings only. It throws an error for non-strings and Unicode character strings. Syntax
String.join(String iterable)
Here is an example
numbers = ['one', 'two', 'three', 'four']
result = ','.join(numbers)
print(result);
List contains non-strings such as int, float or boolean, Then It throws a TypeError
The below code throws an error TypeError
: sequence item 0: expected str instance, int found
numbers = [1,2,3,4]
result = ','.join(numbers)
print(result);
Output:
Traceback (most recent call last):
File "a:\work\python\convertlist-string.py", line 2, in <module>
result = ','.join(numbers)
TypeError: sequence item 0: expected str instance, int found
To make it generic work with any type, use map
inside a join
- use a map, that Iterates the each element and converts to string, Finally returns the list of strings
- pass the string list to join method and returns a Single string
Here is an example to convert a List of Int to a String
numbers = [1,2,3,4]
result = ','.join(map(str, numbers))
print(result);
Output
1,2,3,4
Similarly, You can convert a List of bools to a String with comma separated string
booleanList = [True, False,False, True]
result = ','.join(map(str, booleanList))
print(result);
Output:
True, False,False, True
Generate a String with a hyphen from a List of string
This is another way to generate a list to string.
- Iterate each element using for loop
- add each element to the empty variable with a hyphen(-) symbol
- Finally, Once the iteration is done, remove last hyphen.
numbers = [1,2,3,4]
for number in numbers:
result += number + ','
result = result[:-1] # remove last hyphen
print(result)