Convert a List to String in Python

Jinku Hu Jan 30, 2023 Mar 27, 2019 Python Python String Python List
  1. Convert a str List to String in Python
  2. Convert a Non- str List to a String in Python
Convert a List to 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)
print(StrA)
## 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>
    "".join(a)
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])
"123"

map function

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

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.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python
  • Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • What Is the Difference Between List Methods Append and Extend