当前位置:首页 > 云计算 > 正文内容

python怎么把字符串转化成数字

2022-05-04 03:11:12云计算3

python中的int函数只能把整数字符串转换转换成整数另外可用于取出float的整数部分

可以用float进行转换

测试用例:

>>>s1='123'
>>>s2='1.23'
>>>s3=''
>>>s4=None
>>>int(s1)123
>>>int(s2)ValueError
>>>int(s3)ValueError
>>>int(s4)TypeError
>>>float(s1)123.0
>>>float(s2)1.23
>>>float(s3)ValueError
>>>float(s4)TypeError

顺便一提,float可以转换可以转换科学技术法的数值:

>>>float('1e3')1000.0

推荐学习《python教程》

转换示例:

defstr_to_float(s):
"""字符串转换为float"""
ifsisNone:
return0.0
try:
returnfloat(s)
exceptException:
return0.0

对于带百分号的数值字符串处理方法

>>>s='12%'
>>>float(s.rstrip('%'))/1000.12

对于中文字符的数值字符,可以用unicodedata进行转换。

>>>importunicodedata
>>>unicodedata.numeric('三')3.0
>>>unicodedata.numeric('二十一')TypeError:numeric()argument1mustbeaunicodecharacter,notstr

既名为unicodedata,所以也应该可以对其它语言的数值进行识别。

备注:报错信息只取了重要的部分。

本网站文章仅供交流学习 ,不作为商用, 版权归属原作者,部分文章推送时未能及时与原作者取得联系,若来源标注错误或侵犯到您的权益烦请告知,我们将立即删除.

本文链接:https://www.xibujisuan.cn/8605.html

标签: Python