Python (Scripting) - Convert list to string using join

by
Jeremy Canfield |
Updated: November 18 2024
| Python (Scripting) articles
This is a list that contains values. You can print the list.
#!/usr/bin/python3
list = ["apple", "banana", "orange", "grapes"]
print(list)
Which should return the following.
['apple', 'banana', 'orange', 'grapes']
join can be used to convert the list to a string.
#!/usr/bin/python3
list = ["apple", "banana", "orange", "grapes"]
print(' '.join([x for x in fruits]))
Or more commonly, like this.
#!/usr/bin/python3
list = ["apple", "banana", "orange", "grapes"]
print(f"list = {list}")
list_to_string = ' '.join([elem for elem in list])
print(f"list_to_string = {list_to_string}")
Which should return the following.
list = ['apple', 'banana', 'orange', 'grapes']
list_to_string = apple banana orange grapes
Instead of using a single whitespace as the delimiter, you may want to instead use something like /r/n.
#!/usr/bin/python3
list = ["Hello World", "Goodbye World"]
print(f"list = {list}")
list_to_string = '/r/n'.join([elem for elem in list])
print(f"list_to_string = {list_to_string}")
Which should return the following.
list = ['Hello World', 'Goodbye World']
list_to_string = Hello World/r/nGoodbye World
Or, create a function to convert any list into a string.
list = ["apple", "banana", "orange", "grapes"]
def convert_list_to_string(list):
return ' '.join([elem for elem in list])
list = convert_list_to_string(list )
Sometimes you may have a list that contains a string, perhaps something like this. join can be used to convert the list to a string.
#!/usr/bin/python
mylist = ["this is my list"]
mystring = ''.join(mylist)
print(mystring)
Which should print the following.
this is my list
Did you find this article helpful?
If so, consider buying me a coffee over at