python中的int函數(shù)
只能把整數(shù)字符串轉(zhuǎn)換轉(zhuǎn)換成整數(shù)
另外可用于取出float的整數(shù)部分
可以用float進(jìn)行轉(zhuǎn)換
測(cè)試用例:
>>>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可以轉(zhuǎn)換可以轉(zhuǎn)換科學(xué)技術(shù)法的數(shù)值:
>>>float('1e3')1000.0
轉(zhuǎn)換示例:
defstr_to_float(s):
"""字符串轉(zhuǎn)換為float"""
ifsisNone:
return0.0
try:
returnfloat(s)
exceptException:
return0.0
對(duì)于帶百分號(hào)的數(shù)值字符串處理方法
>>>s='12%'
>>>float(s.rstrip('%'))/1000.12
對(duì)于中文字符的數(shù)值字符,可以用unicodedata進(jìn)行轉(zhuǎn)換。
>>>importunicodedata
>>>unicodedata.numeric('三')3.0
>>>unicodedata.numeric('二十一')TypeError:numeric()argument1mustbeaunicodecharacter,notstr
既名為unicodedata,所以也應(yīng)該可以對(duì)其它語言的數(shù)值進(jìn)行識(shí)別。
備注:報(bào)錯(cuò)信息只取了重要的部分。
以上內(nèi)容為大家介紹了python培訓(xùn)之怎么把字符串轉(zhuǎn)化成數(shù)字,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。