ID : 18
viewed : 198
Tags : PythonPython StringPython List
90
str
List to String in PythonWe 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"
str
List to a String in PythonThe 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.
>>> a = [1,2,3] >>> "".join([str(_) for _ in a]) "123"
>>> 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.