Home > front end >  I need to convert the given list of String format to a single list
I need to convert the given list of String format to a single list

Time:10-05

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:

  1. Used for loop to read the content in list a.
  2. Then again used a for loop to read each character in the string of i.
  3. Then used try to try if i can typecast j into int so that it would only add the numbers to nums_str.
  4. Then appended the nums_str to the list a1 if j if = "," or "]".
  5. Continued the above process on each item in a.
  6. After the for loop gets over, i change a to copy of a1.

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']
  • Related