Python - Ways to merge strings into list


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)

Updated on: 06-Aug-2020

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements