Python | Ways to combine strings into a list

When developing an application, many scenarios arise when we need to work with a string and transform it into some kind of changing data structure, say, list . There are several ways to convert strings to list based on requirements. Let`s figure it out better with examples.


Method # 1: Using Ast

# Python code to combine all lines into one list.

  
# Import

import ast

 
# Line initialization

str1 = "` Geeks`, `for`,` Geeks` "

str2 = "` paras.j`, `jain.l` "

str3 = " `india` "

  

  
# List initialization

list = []

 
# Expanding to a single list

for x in (str1, str2, str3):

list . extend (ast.literal_eval (x))

 
# printout

print ( list )

Exit:

 [`Geeks`,` for`, `Geeks`,` paras.j`, `jain.l`,` i`, `n`,` d`, `i`,` a`] 


Method # 2: Using Eval

# Python code to combine all lines into one list.

 
# Initializing strings

str1 = "[` Geeks`, `for`,` Geeks`] "

str2 = " [`paras .j`, `jain.l`]"

str3 = "[` india`] "

  

  

out = [str1 , str2, str3]

 

out   = eval ( `+` . join (out))

 
# printout

print (out)

Exit:

 [`Geeks`,` for`, ` Geeks`, `paras.j`,` jain.l`, `india`] 

# Python code to combine all lines into one list.

 
# Line initialization

str1 = "` Geeks`, `for`,` Geeks` "

str2 = "` 121`, `142`"

< p> str3 = "` extend`, `India`"

 

 

out = [str1, str2, str3]

 

out = eval ( ` + ` . join (out))

 
# print out

print ( list (out) )

Exit:

 [` Geeks`, `for`,` Geeks121`, `142extend`,` India`]