新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python中如何將字符串強制轉(zhuǎn)為數(shù)字
python中強制將字符串轉(zhuǎn)換為數(shù)字的方法:

1、python中可以使用int()函數(shù)將字符串轉(zhuǎn)換為整型數(shù)字,int() 函數(shù)用于將一個字符串或數(shù)字轉(zhuǎn)換為整型。
int() 方法的語法:
class int(x, base=10)
參數(shù)
x -- 字符串或數(shù)字。
base -- 進制數(shù),默認十進制。
返回值:返回整型數(shù)據(jù)。
示例:
>>> s1 = '999' >>> if s1.isdigit(): num1 = int(s1) >>> type(num1)>>> num1 999
2、使用float()函數(shù)將字符串轉(zhuǎn)換為浮點數(shù)
float() 函數(shù)用于將整數(shù)和字符串轉(zhuǎn)換成浮點數(shù)。
float()方法語法:
class float([x])
參數(shù)
x -- 整數(shù)或字符串
返回值:返回浮點數(shù)。
示例:
>>> s2 = '999.888' >>> if s2.isdigit(): num2 = float(s2) >>> type(num2) Traceback (most recent call last): File "", line 1, in type(num2) NameError: name 'num2' is not defined >>> >>> s2.isdigit() False >>> s2 = '999.888' >>> num2 = float(s2) >>> type(num2) >>> num2 999.888 >>>
當(dāng)前名稱:創(chuàng)新互聯(lián)Python教程:python中如何將字符串強制轉(zhuǎn)為數(shù)字
網(wǎng)頁路徑:http://m.fisionsoft.com.cn/article/coepeso.html


咨詢
建站咨詢
