Vignesh Karthikeyan Vignesh Karthikeyan - 1 month ago 9
Python Question

How to convert a string into a list/tuple without losing the type of the values in the string?

If i have

a = "3.14, ABCF , 2.16"


and type(a) returns "str"

how may i convert this into a list or tuple and keep the type integrity of elements inside.(ex: running through the collection and check type should return float, string, float, respectively)

Answer

I did this using regular expression

import re
a = "3.14, ABCF , 2.16 , 9"
b=a.split(",")
for c in b:
    x=c.strip()
    if x.isdigit():
        print("int")
    elif bool(re.search('[a-zA-Z]+', x)):
        print("string")
    elif bool(re.search('[0-9.]+', x)):
        print("float")

OUTPUT :

float
string
float
int

OR this

from ast import literal_eval

def get_type(data):
    try:
        return type(literal_eval(data))
    except (ValueError, SyntaxError):
        # A string, so return str
        return str

a = "3.14, ABCF , 2.16 , 9"
b=a.split(",")
for c in b:
    x=c.strip()
    print(get_type(x))

OUTPUT:

<class 'float'>
<class 'str'>
<class 'float'>
<class 'int'>
Comments