简体   繁体   中英

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)

I did this using regular expression

import re
a = "3.14, ABCF , 2.16 , 9"
b=a.split(",")  #break string
for c in b:
    x=c.strip() # removes whitespace character
    if x.isdigit(): #return bool value
        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

By using python ast library

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, True"
b=a.split(",")
for c in b:
    x=c.strip()
    print(get_type(x))

OUTPUT:

<class 'float'>
<class 'str'>
<class 'float'>
<class 'int'>
<class 'bool'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM