Problem Statement: Given a random Python list (the list can be of numbers, characters, strings, or combinations of all three of them). Convert it to a Python string.
For Example:
- [1, 2, 3, 5, 7] -> 12357
- [‘A’, ‘B’, ‘C’, ‘D’, ‘E’] -> ABCDE
- [“Scholar”, “Basta”] -> ScholarBasta
- [“Scholar”, “Basta”, ‘@’, 2021] -> ScholarBasta@2021
Solution: A Python program which will convert a list to a string. The following the different ways/methods to convert a Python List to a String:
Method 1: Iterate through the list and add each element to a blank string
# Given Python List
my_list = ['S','c','h','o','l','a','r','B','a','s','t','a']
# Empty String
string = ""
# Conversion (list -> string)
for item in my_list:
string = string + item
# Print Output
print(string)
Output:
ScholarBasta
Method 2: Using join() function
The join() function joins all the items in the list separated by the string token i.e. ” ” (space), or “,” (comma), etc.
# Given Python List
my_list = ["Scholar","Basta",":","Fellowships","Assignments","and","Tutorials"]
# Empty String
string = ""
# Conversion (list -> string) & space (" ") is a string_token here
string = " ".join(my_list)
# Print Output
print(string)
Output:
Scholar Basta : Fellowships Assignments and Tutorials
If the list contains strings and integers as its elements then the above method will not work. We have to convert each element of the list to a string before adding it to the string.
Method 3: Using list comprehension
# Given Python List
my_list = ["I","can","write",10,"pages","in","an","hour","."]
# Empty String
string = ""
# Conversion (list -> string)
string = " ".join([str(item) for item in my_list])
# Print Output
print(string)
Output:
I can write 10 pages in an hour .
Method 4: Using map() function
# Given Python List
my_list = ["Table of 11:",11,22,33,44,55,66,77,88,99,110]
# Empty String
string = ""
# Conversion (list -> string) & newline character ("\n") is a string_token here
string = "\n".join(map(str, my_list))
# Print Output
print(string)
Output:
Table of 11:
11
22
33
44
55
66
77
88
99
110
Method 5: Using strip() we can convert a list to a comma ‘,’ separated string
# Given Python List
my_list = ["Apple","Banana","Cherries","Dates","Elderberries"]
# Empty String
string = ""
# Conversion (list -> string)
string = str(my_list).strip("[]")
# Print Output
print(string)
Output:
‘Apple’, ‘Banana’, ‘Cherries’, ‘Dates’, ‘Elderberries’