Sometimes, while working with data, we can have a problem in which we need to convert data in string into a list and string contains elements from different data types like boolean. This problem can occur in domains in which lot of data types are used. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension +
split() + strip()
The combination of above methods can be used to solve this problem. In this, we perform the split of elements and then strip the stray character to convert data types and compile the whole logic of list construction using list comprehension.
The original string is : 'gfg', 'is', True, 'best', False List after conversion from string : ["'gfg'", "'is'", True, "'best'", False]
Method #2 : Using
This inbuilt function auto-detects the data type and performs the conversion. It is single phrase solution and also provides solution even if integers are in string and hence recommended for this solution.
The original string is : 'gfg', 'is', True, 'best', False, 1, 2 List after conversion from string : ["'gfg'", "'is'", True, "'best'", False, 1, 2]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course