2

for eg I have the List:

old = ['Savannah', '234Today', '4.5678', '23456','0.2342429'] 

How can I convert it to a list with elements with the default type

to:

new = ['Savannah', '234Today', 4.5678, 23456,0.2342429] 

The new list will have the elements with their default type be it float, int, long

Any help is Appreciated! Thank you

1 Answer 1

7

You can use ast.literal_eval and some exception handling:

>>> from ast import literal_eval >>> lis = ['Savannah', '234Today', '4.5678', '23456','0.2342429'] def solve(x): try: return literal_eval(x) except (ValueError, SyntaxError): return x ... >>> map(solve, lis) ['Savannah', '234Today', 4.5678, 23456, 0.2342429] 
Sign up to request clarification or add additional context in comments.

1 Comment

Arg, was messing around with literal_eval but couldn't figure it out :p. +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.