繁体   English   中英

如何将字符串的值转换为其特定的数据类型? '5' -> 5 或 'a' -> a

[英]How to convert value of a String into it's specific datatype? '5' -> 5 OR 'a' -> a

考虑我将输入作为 python 列表,它包含['1', '5', 't', 'John', '3.18']类的值

如何将每个值转换为其特定的数据类型?

像这样的东西

String '1' -> Integer 1

String 't' -> Char 't'

String '3.18' -> Float 3.18

请求宽恕,而不是许可!

def to_type(x):
    try:
        return int(x)
    except ValueError:
        pass
    try:
        return float(x)
    except ValueError:
        pass
    return x

converted = [to_type(x) for x in your_list]
    values = ['1', '5', 't', 'John', '3.18']
    x=[int(value) if value.isdigit() else float(value) if value.replace('.', '', 1).isdigit() else value for value in values]
    print(x)

Output:
[1, 5, 't', 'John', 3.18]
  1. 如果提供的值是 int,它会进入 if value.isdigit() 并将 value 转换为 int。
  2. 如果 value 是 float 则 value.isdigit() 为 false 并进入 if value.replace('.', '', 1).isdigit() where 。 将被替换并验证是否为数字。 如果是数字,则转换为浮点数。

值列表中的数据类型不清楚,因此可能会出现意外错误。

values = ['1', '5', 't', 'John', '3.18']

def change_type(value):
    if str(value).isdigit():
        return int(value)
    try:
        return float(value)
    except ValueError:
        return value

[change_type(value) for value in values]
[1, 5, 't', 'John', 3.18]

您可以使用try except结构来检查对象是否可以转换为特定的数据类型:

l1 = ['1', '5', 't', 'John', '3.18']

#First object can be converted to int
try:
    l1[0] = int(l1[0])
except ValueError as e:
    print(e)

#Second one not
try:
    l1[2] = int(l1[2])
except ValueError as e:
    print(e)
    
print(l1)

在这种情况下,输出将是:

invalid literal for int() with base 10: 't'
[1, '5', 't', 'John', '3.18']

您可以使用int()float()bool() ...等函数进行多种检查。您可能需要查看 Python 官方文档以查看所有可能性。

尝试这个:

a = "123"
b = int(a)

您可以使用ast.literal_eval()函数以 Python 解释器的方式解析列表的元素。 下面的代码也适用于字符串元组。

from ast import literal_eval

def convert_seq(seq):
    """Return sequence of strings into one with each parsed as a literal value."""
    def convert_elem(elem):
        try:
            return literal_eval(elem)
        except ValueError:
            return elem
    return type(seq)(map(convert_elem, seq))

r = convert_seq(['1', '5', 't', 'John', '3.18', '"100"'])
print(r)  # -> [1, 5, 't', 'John', 3.18, '100']

尝试这个:

def check_(x):
    if "." in x:
        new_x = x.replace(".","",1)
        if new_x.isdigit():
            xx= float(x)
            return "float",xx
    if x.isdigit():
            xx=int(x)
            return "int",xx
    else: 
        if len(x)>1:
            xx=x
            return "String",xx
        else:
            xx= x
            return "char",xx

var_ = "55.3"

print(check_(var_)[0])
print(check_(var_)[1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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