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.
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
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
>>> 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
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
"".join() iterates all the elements in the
map object and returns the concatenated elements as a 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
- 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