Python | Convert a string of dissimilar type to a list

Method # 1: Using List Comprehension + split () + strip ()
A combination of the above methods can be used to solve this problem. In this, we perform element separation and then strip the wildcard for data type conversion and compile all the list building logic using a list comprehension.

# Python3 demo code works
# Convert heterogeneous type string to list
# using list comprehension + split () + strip ()

 
# initialization string

test_str = "` gfg`, `is`, True,` best` , False "

  
# print original line

print ( "The original string is : " + test_str)

  
# Convert heterogeneous type string to list
# using list comprehension + split () + strip ()

res = [ele.strip ( ) if ele.strip (). startswith ( "` " ) else ele = = ` True `

for ele in test_str.split ( `,` )]

  
# print result

print ( "List after conversion from string:" + str (res))

Output:

 The original string is: `gfg`,` is`, True , `best`, False List after conversion from string: [" `gfg`", "` is` ", True," best` ", False] 

Method # 2: Using eval()
This built-in function automatically detects the data type and performs the conversion. This is a one-phrase solution, and also a solution even if the integers are in a string and therefore recommended for this solution.

# Python3 code to demonstrate how it works
# Convert a heterogeneous type string to a list
# using eval ()

 
# initialization string

test_str = " `gfg`,` is`, True, `best`, False, 1, 2"

 
# print original line

print ( "The original string is:" + test_ str)

 
# Convert heterogeneous type string to list
# using eval ()

res = list ( eval (test_str))

 
# print result

print ( "List after conversion from string:" + str (res))

Output:

 The original string is: `gfg`,` is`, True, `best`, False, 1, 2 List after conversion from string: [" `gfg`", "` is` ", True," best` ", False, 1, 2]