Create a comma-separated string from a list of strings in Python
This post will discuss how to create a comma-separated string from a list of strings in Python.
1. Using str.join() function
The preferred approach to creating a comma-separated string from a list of strings is with the str.join() function. This efficiently concatenates each member of the list using a separator and returns a new string. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': chars = ['A', 'B', 'C', 'D', 'E'] delim = ',' s = delim.join(chars) print(s) # A,B,C,D,E |
If you have a list of integers, you should convert each element to a string first. This can be efficiently done using the map() function.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': nums = [1, 2, 3, 4, 5] delim = ',' s = delim.join(map(str, nums)) print(s) # 1,2,3,4,5 |
2. Using reduce() function
Following is a simple example demonstrating the usage of the reduce() function to create a comma-separated string from a list of strings:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
from functools import reduce if __name__ == '__main__': chars = ['A', 'B', 'C', 'D', 'E'] delim = ',' add = lambda x, y: x + delim + y s = reduce(add, chars) print(s) # A,B,C,D,E |
3. Using for-loop
Finally, you can iterate over the list using a for-loop and concatenate each member of the list into a new string separated by a separator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from functools import reduce if __name__ == '__main__': chars = ['A', 'B', 'C', 'D', 'E'] delim = ',' s = '' for str in chars: s += (str + delim) print(s[:-1]) # A,B,C,D,E |
That’s all about creating a comma-separated string from a list of strings in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)