TypeError: can only concatenate list (not “str”) to list
But some times it’s required to combine these two types, what is the solution?
The solution is to convert one data type to other before doing a combination.
How to convert a list data type to string data type in Python?
Use inbuilt python function join to convert a list to a string
Syntax for join function:
separator.join(sequence)
“separator” from above can be any character you specify to separate the sequence of strings variable in join function “sequence”
Join function examples:
I have a following list
list1 = [“surendra”, “is”, “a”, “good”, “programmer”]
and string to separate above list once it’s converted to string is ‘-‘. Now joining above list using join function:
Str1 = ‘-‘.join(list1)
print Str1
Output:
surendra-is-a-good-programmer
You can change the separator what ever you want, even a group of chars as well.
How to convert a string data type to list data type in Python?
Use inbuilt python function “split”
Syntax for split function:
string.split(‘seperator’)
“string” in the above syntax is a string which you want to split using split function and “separator” in the split function is to separate the list elements.
Example:
Str1=’surendra-is-a-good-programmer’
list1 = Str1.split(‘-‘)
print list1
Output:
[‘surendra’, ‘is’, ‘a’, ‘good’, ‘programmer’]
Hope it helps you people. Please share your thoughts on this.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018