Methods to Convert a List to String using Python
Different methods to convert a Python List to String. We will be explaining the code example that will be using the join() function of the Python string.
# define a list
my_list = ['D', 'e', 'v', 's', 'h', 'e', 'e', 't']
# use join() function to convert list to string
result = "".join(my_list)
print(result)
Output
Devsheet
- Defined a Python List my_list.
- Using "".join(my_list), to concatenate the list items and create a string from them.
- Print the result.
Solution 1: Convert using join() function
In Python, the built-in function join() can be used to convert a list of strings into a single string. This function is useful when you need to manipulate or display a list of strings as a single entity.
For example, you might want to convert a list of customer names into a single string that can be displayed in a customer list report. Or you might want to convert a list of filenames into a single string that can be passed to a file-processing program.
Syntax
"".join(List)
Code example
name_parts = ['Justin', 'Tray', 'Lambart']
print("List is: ", name_parts)
name_str = " ".join(name_parts)
print("Final string is: ", name_str)
Output
List is: ['Justin', 'Tray', 'Lambart']
Final string is: Justin Tray Lambart
This code creates a list called name_parts containing the strings 'Justin', 'Tray', and 'Lambart'. It then joins these strings together into a single string called name_str using the space character as a separator.
Solution 2: Use For loop to convert List to String
If you do not want to use any method to convert a List to String, you can also use Python For loop. We will be applying for loop on the list and in each iteration, we will append the item to String variable result.
my_list = ['D', 'e', 'v', 's', 'h', 'e', 'e', 't']
result = ''
for item in my_list:
result += item
print(result)
Output
Devsheet
- Here, We have creates a list called my_list.
- Then, We created an empty string called result.
- We loop through each item in my_list.
- We add each item to the We print the result string. string.
- We print the result string.
words = ["Hello", "World"]
result = " ".join(words)
print(result)
# -> Hello World
- Convert all string values in a list to integers using python
- Convert a List of Strings to List of Integers in Python
- Convert JSON string to Python collections - like list, dictionaries
- Convert Python Collections - List, Dict to JSON String
- Convert List of Tuples to JSON string in Python
- [Python] Using comprehension expression to convert list of dictionaries to nested dictionary
- Convert pandas DataFrame to List of dictionaries python