need to convert this list :
a = ["['0221', '02194', '02211']"]
type = list
to this list :
a = ['0221', '02194', '02211']
type = list
CodePudding user response:
If your new to python this code would seem like very complicated, but i will explain whats in this piece of code:
a=["['0221', '02194', '02211']"]
a1=[]
nums_str=""
for i in a:
for j in i:
try:
if j=="," or j=="]":
a1.append(nums_str)
nums_str=""
nums=int(j)
nums_str =str(nums)
except Exception as e:
pass
else:
a=a1.copy()
print(a)
print(type(a))
Steps:
- Used
for loop
to read the content inlist a
. - Then again used a
for loop
to read each character in the string ofi
. - Then used
try
to try if i can typecastj
intoint
so that it would only add the numbers tonums_str
. - Then appended the
nums_str
to the lista1
ifj
if = "," or "]". - Continued the above process on each item in
a
. - After the
for loop
gets over, i changea
to copy ofa1
.
CodePudding user response:
You can use astliteral_eval to convert strings to Python data structures. In this case, we want to convert the first element in the list a to a list.
import ast
a = ast.literal_eval(a[0])
print(a)
# ['0221', '02194', '02211']
Note: Python built-in function eval also works but it's considered unsafe on arbitray strings. With eval:
a = eval(a[0]) # same desired output
CodePudding user response:
You can try list comprehension:
a = a[0][2:][:-2].split("', '")
output:
a = ['0221', '02194', '02211']