Python-字符串与数值类型的互相转换

78 阅读1分钟

1. 数值转字符串

1.1 str()

a = 1
b = 1.5
str_a = str(a)
str_b = str(b)

# str_a = ''+a 报错 TypeError: can only concatenate str (not "int") to str
# str_b = ''+b 报错 TypeError: can only concatenate str (not "float") to str

1.2 f-string

a = 1
b = 1.5

str_a = f'{a}'
str_b = f'{b}'
# str_a = ''+a 报错 TypeError: can only concatenate str (not "int") to str
# str_b = ''+b 报错 TypeError: can only concatenate str (not "float") to str

1.3 字符串直接拼接不可用

a = 1
b = 1.5


str_a = ''+a # 报错 TypeError: can only concatenate str (not "int") to str
str_b = ''+b # 报错 TypeError: can only concatenate str (not "float") to str

2. 字符串转数值

2.1 已知数值类型

str_a = '1'
str_b = '1.5'
a = int(str_a)
b = float(str_b)

2.2 不确定数值类型

str_a = '1'
str_b = '1.5'
a = int(str_a)
b = float(str_b)
def str_to_num(s):
    try:
        a = int(s)
        return a
    except ValueError as e:
        pass    
    try:
        a = float(s)
        return a
    except ValueError as e:
        pass
    return s