新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python怎么把字符串轉(zhuǎn)化成數(shù)字
python中的int函數(shù)
只能把整數(shù)字符串轉(zhuǎn)換轉(zhuǎn)換成整數(shù)
另外可用于取出float的整數(shù)部分

可以用float進行轉(zhuǎn)換
測試用例:
>>> 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推薦學(xué)習(xí)《python教程》
轉(zhuǎn)換示例:
def str_to_float( s): """字符串轉(zhuǎn)換為float""" if s is None: return 0.0 try: return float(s) except Exception: return 0.0
對于帶百分號的數(shù)值字符串處理方法
>>> s='12%'
>>> float(s.rstrip('%'))/1000.12對于中文字符的數(shù)值字符,可以用unicodedata進行轉(zhuǎn)換。
>>> import unicodedata
>>> unicodedata.numeric('三')3.0
>>> unicodedata.numeric('二十一')TypeError: numeric() argument 1 must be a unicode character, not str既名為unicodedata,所以也應(yīng)該可以對其它語言的數(shù)值進行識別。
備注:報錯信息只取了重要的部分。
分享名稱:創(chuàng)新互聯(lián)Python教程:python怎么把字符串轉(zhuǎn)化成數(shù)字
文章網(wǎng)址:http://fisionsoft.com.cn/article/dppcjcc.html


咨詢
建站咨詢
