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
轉換示例:
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,所以也應該可以對其它語言的數值進行識別。
備注:報錯信息只取了重要的部分。
以上內容為大家介紹了python培訓之怎么把字符串轉化成數字,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。