Convert a List to a Python string
This post will discuss how to convert a list to a string in Python.
The preferred and fast way to concatenate the strings in iterable is with the str.join() function. The following code example shows how to implement this:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': chars = ['1', '2', '3'] s = ''.join(chars) print(s) # 123 |
Note that TypeError will be raised for any numeric values in iterable. To convert a list of integers to a string, you have to first convert each of the non-string values present in the iterable to a string. You can do this in the following ways:
1. Using Generator Expression
You can use a generator to easily convert the list of integers to a string, as shown below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': nums = [1, 2, 3] s = ''.join(str(x) for x in nums) print(s) # 123 |
2. Using map() function
It is preferable to use the map() function instead, which efficiently converts a list of integers to a string.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': nums = [1, 2, 3] s = ''.join(map(str, nums)) print(s) # 123 |
That’s all about converting a List to a string 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 :)