Change language

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] 

Python | Convert a string of dissimilar type to a list Python functions: Questions

Python | Convert a string of dissimilar type to a list String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method