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” 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)
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” 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.
list1 = Str1.split(‘-‘)
[‘surendra’, ‘is’, ‘a’, ‘good’, ‘programmer’]
Hope it helps you people. Please share your thoughts on this.
Latest posts by Surendra Anne (see all)
- 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
- wget download a file to a directory in Linux/Unix - June 4, 2018
- GIT: How to compare two GIT branches? - June 3, 2018
- Online training on Linux Bash shell scripting - February 8, 2018