python培训之怎么把字符串转化成数字

发布时间:2022-08-10 09:45:43 人气:174 作者:多测师

  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

python培训之怎么把字符串转化成数字

  顺便一提,float可以转换可以转换科学技术法的数值:

  >>> float('1e3')1000.0

  转换示例:

  def str_to_float( s):

  """字符串转换为float"""

  if s is None:

  return 0.0

  try:

  return float(s)

  except Exception:

  return 0.0

  对于带百分号的数值字符串处理方法

  >>> s='12%'

  >>> float(s.rstrip('%'))/1000.12

  对于中文字符的数值字符,可以用unicodedata进行转换。

  >>> import unicodedata

  >>> unicodedata.numeric('三')3.0

  >>> unicodedata.numeric('二十一')TypeError: numeric() argument 1 must be a unicode character, not str

  既名为unicodedata,所以也应该可以对其它语言的数值进行识别。

  备注:报错信息只取了重要的部分。

  以上内容为大家介绍了python培训之怎么把字符串转化成数字,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线