Convert a List to String in Python

  1. Convert a str List to String in Python
  2. Convert a Non- str List to a String in Python

Convert a str List to String in Python

We could use str.join() method to convert a list that has str data type elements to a string.

For example,

A = ["a", "b", "c"]
StrA = "".join(A)
## StrA is "abc"

join method concatenates any number of strings, the string whose method is called is inserted in between each given string. As shown in the example, the string "", an empty string, is inserted between the list elements.

If you want a space " " is added between the elements, then you should use

StrA = " ".join(A)
## StrA is "a b c"

Convert a Non- str List to a String in Python

The join method requires the str data type as the given parameters. Therefore, if you try to join the int type list, you will get the TypeError

>>> a = [1,2,3]
>>> "".join(a)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

The int type should be converted to str type before it is joined.

List comprehension

>>> a = [1,2,3]
>>> "".join([str(_) for _ in a])

map function

>>> a = [1,2,3]
>>> "".join(map(str, a))

map function applies the str function to all the items in the list a, and it returns an iterable map object.

"".join() iterates all the elements in the map object and returns the concatenated elements as a string.

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Convert String to Boolean in Python
  • Generate Random Strings in Python
  • Related Article - Python List

  • Check Variable Is String or Not in Python
  • Append One String to Another in Python