python字符串转换为数字的两种方法及前提条件

将python的字符串转换为数字的开发需求在python的web应用开发当中可能会比较常应用到,比如通过url传递参数给后端时,后端程序捕捉到该参数所获取到的数据一般为字符串类型,需要运算的话往往就需要对其进行相应的转换。除此之外,input()函数捕捉到的数据也一般为字符串类型。下面介绍两种将字符串转换成数字类型的方法。


python字符串转换为数字的两种方法

这里主要还是介绍将字符串转换成整型数值和浮点型数值的方法,分别通过int()和float()两个转换函数,使用这int()和float()函数将python字符串转换成数值的两个前提条件是:

  1. 字符串必须是数字型的字符串;
  2. 浮点型的字符串不能用int()函数来转换,整型数值的字符串则可以用float()来转换

实例

相关的代码解析可以查看实例中的注释。


>>> a = "1.2"
>>> type(a)
<class 'str'>
>>> b = int(a) #浮点型数值的字符串不能用int()函数来转换
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.2'
>>> b = float(a)
>>> b
1.2
>>> type(b)
<class 'float'>
>>> a #注意,变量a的值并未发生改变,为什么呢?
'1.2'
>>> c = "3"
>>> d = int(c)
>>> d
3
>>> type(d)
<class 'int'>
>>> e = float(c) #整型值的字符串可以用float()函数来转换
>>> e
3.0
>>> type(e)
<class 'float'>
>>> f = "hello"
>>> int(f) #非数值型的字符串不可以用相关的转换函数来转换成数值型数据
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hello'
>>> float(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'hello'

笨鸟问答 / python问答 :





Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.