Python - Ways to merge strings into list

PythonServer Side ProgrammingProgramming

While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list.

Example

# Importing ast library
import ast
# Initialization of strings
str1 ="'Python', 'for', 'fun'"
str2 ="'vishesh', 'ved'"
str3 ="'Programmer'"
# Initialization of list
list = []
# Extending into single list
for x in (str1, str2, str3):
   list.extend(ast.literal_eval(x))
# printing output
print(list)
# using eval
# Initialization of strings
str1 ="['python, 'for', ''fun']"
str2 ="['vishesh', 'ved']"
str3 ="['programmer']"
out = [str1, str2, str3]
out = eval('+'.join(out))
# printing output
print(out)
raja
Published on 06-Aug-2020 17:57:00
Advertisements