AppDividend
Latest Code Tutorials

Python List to String: How to Convert List to String

0

Python list to string

To convert the list to string in Python, use the join() function. The join() function takes one parameter that is the list, and returns the string. Python String join() method returns a string by joining all the items of an iterable, separated by a string separator if provided.

# app.py

data = ["Millie", "Bobby", "Brown", "is", "Enola", "Holmes"]


def listToString(list):
    str1 = " "
    return (str1.join(list))


convertedStr = listToString(data)
print(convertedStr)

Output

Millie Bobby Brown is Enola Holmes

In this code, we have defined a list and a user-defined function. The function listToString() function accepts the list and passes the list to the join() method. The join() method is called upon an empty string, and it returns the string.

How to convert a List of Chars to String

To convert the list of chars to string in Python, use the join() method.

# app.py

charList = ["M", "I", "L", "L", "I", "E"]

charStr = ''.join(charList)

print(charStr)

Output

MILLIE

But what if the list contains both string and int as its items. Let’s see that scenario.

# app.py

charList = ["M", "I", "L", "L", "I", "E", 1, 2, 3]

charStr = ''.join(charList)

print(charStr)

Output

Traceback (most recent call last):
  File "app.py", line 3, in <module>
    charStr = ''.join(charList)
TypeError: sequence item 6: expected str instance, int found

We got an error like this. TypeError: sequence item 6: expected str instance, int found.

The solution is to convert it to the string while adding to a string.

# app.py

charList = ["M", "I", "L", "L", "I", "E", 1, 2, 3]

listToStr = ''.join([str(elem) for elem in charList])

print(listToStr)

Output

MILLIE123

Convert List to String using map()

Python map() method executes the specified function for each element in an iterable. The element is sent to the function as a parameter.

# app.py

strList = ["Millie", "Bobby", "Brown", "is", "Enola", "Holmes", 1, 2, 3]

listToStr = ' '.join(map(str, strList))

print(listToStr)

Output

Millie Bobby Brown is Enola Holmes 1 2 3

Comma-separated string from a list of numbers

To convert a comma-separated string from the list, use the join() method.

# app.py

strList = ["Millie", "Bobby", "Brown", "is", "Enola", "Holmes", 1, 2, 3]

listToStr = ','.join(map(str, strList))

print(listToStr)

Output

Millie,Bobby,Brown,is,Enola,Holmes,1,2,3

That is it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.