1

From a python function, I get the following output:

['(0.412169, mississippi)']

The type indicates that it is a list. I want to extract the values from the list and save it as separate elements. I tried various functions to convert list to tuple, list to str, extracting the element by Index from the tuple or str, nothing worked out. When I try to extract the element by index, I either get '(' for the first element index 0, or when I try to extract through a iterator function, I get all the values split up like the full data set as a string.

How do I get values separately.

2
  • As the question has been closed, here the solution: You have first to get rid of the paranthesis in the string expression: string = ['(0.412169, mississippi)'] elems = string[0].replace('(','').replace(')','').split(',') Output: ['0.412169', ' mississippi'] Commented May 20, 2020 at 9:21
  • How'd you get that string in the first place? Can that be changed to something more parseable at the source? Commented May 20, 2020 at 9:25

2 Answers 2

2

You can iterate over your data, remove the parentheses using slicing and split the string by comma to create a list, which will be appended to your output payload:

data = ['(0.412169, mississippi)', '(0.412180, NY)']
extracted_values = []
for d in data:
    extracted_values += d[1:-1].split(",")
print(extracted_values) 
# output: ['0.412169', ' mississippi', '0.412180', ' NY']
Sign up to request clarification or add additional context in comments.

Comments

-1

Your list content a string, not a list. If you want to extract the content of a string, use the "eval" statement

my_tuple = eval("(0.412169, 'mississippi')")

Note that the "eval" function can be dangerous, because if your string content python code, it could be executed.

2 Comments

Right, use ast.literal_eval instead!
OP is having ['(0.412169, mississippi)'] to start with. Notice there are no quotes around string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.