python

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
  1. Defined a Python List my_list.
  2. Using "".join(my_list), to concatenate the list items and create a string from them.
  3. 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
  1. Here, We have creates a list called my_list.
  2. Then, We created an empty string called result.
  3. We loop through each item in my_list.
  4. We add each item to the We print the result string. string.
  5. We print the result string.
words = ["Hello", "World"]

result = " ".join(words)

print(result)

# -> Hello World
Here we are generating a string from Python List items with space between each item.
Was this helpful?