This article will show you how to convert lists to a string in the Python programming language.
Why would you want to convert a list to a string? Most commonly, because you want to print it or because you want to store it in a database text field or a text file.
Converting List to String in Python
The join() string method will take a list or iterable in Python and join each element, using the given string as a separator between each element.
# Define a list of strings myList = ['apple', 'banana', 'orange'] # Convert the list to a single string by merging the values myString = ','.join(myList)
Above, a list of strings is converted to a single string with a comma separating the values – the separator string (‘,’) has a join() method, which will insert that separator string in between each value in the list and return the result, which is assigned to the variable myString.
Numbers and Other Types
Python variables of other types can be converted to strings which can be merged using the str() function, which converts a given variable or value into a string.
# Define a list of numbers myList = [1, 2, 3, 4] # Convert the list to a string by using a for loop to run the str() function on each element in the lsit myString = ','.join(str(e) for e in myList) # myString now has the value "1,2,3,4"
Converting String to List in Python
Want to do the reverse? Here’s how to convert a string into a list:
# Define a string with commas separating the words myString = "these,are,words" # Convert to list myList = myString.split(",") # myList now has the value ['these', 'are', 'words']
The above will convert the string to a list, with each item being one of the comma-separated values in the list (the commas will be omitted).
By default, the split() method will separate the words in the string by the white-space (spaces, tabs, newlines) between them if no separator is supplied,
Numbers and Other Types
Strings containing values that you wish to be interpreted as into lists of non-string values can be converted like so:
# Define a string with a comma separated list of numbers myString = "1,2,3,4" # Convert to a list of number variables (not strings!) myList = list(int(e) for e in myString.split(",")) # myList now has the value [1, 2, 3, 4]
Above, the list() function is used to convert the result of the string split() method – after the int() function has been run on each element from the split() method to convert it to an integer.
In place of int() – other conversion functions can be used to get other data types – see our article on converting data types here.