在 Python 中如何将字符串转换为整数

开发 后端
类似于内置的 str() 方法,Python 语言中有一个很好用的 int() 方法,可以将字符串对象作为参数,并返回一个整数。

 类似于内置的 str() 方法,Python 语言中有一个很好用的 int() 方法,可以将字符串对象作为参数,并返回一个整数。

[[442867]]

用法示例:

 

  1. # Here age is a string object 
  2. age = "18" 
  3. print(age) 
  4.  
  5. # Converting a string to an integer 
  6. int_age = int(age) 
  7. print(int_age) 

 

输出:

 

  1. 18 
  2. 18 

 

尽管输出结果看起来相似,但是,请注意第一行是字符串对象,而后一行是整数对象。在下一个示例中将进一步说明这一点:

 

  1. age = "18" 
  2. print(age + 2) 

 

输出:

 

  1. Traceback (most recent call last): 
  2.   File "<stdin>", line 1, in <module> 
  3. TypeError: cannot concatenate 'str' and 'int' objects 

 

通过这个报错,你应该明白,你需要先将 age 对象转换为整数,然后再向其中添加内容。

 

  1. age = "18" 
  2. age_int = int(age) 
  3. print(age_int + 2) 

 

输出:

 

  1. 20 

但是,请记住以下特殊情况:

  • 浮点数(带小数部分的整数)作为参数,将返回该浮点数四舍五入后最接近的整数。例如:print(int(7.9)) 的打印结果是 7。另一方面,print(int("7.9")) 将报错,因为不能将作为字符串对象的浮点数转换为整数。

 

  1. Traceback (most recent call last): 
  2.   File "<stdin>", line 1, in <module> 
  3. ValueError: invalid literal for int() with base 10: '7.9' 

 

  • 单词作为参数时,将返回相同的错误。例如,print(int("one")) 将返回:

 

  1. Traceback (most recent call last): 
  2.   File "<stdin>", line 1, in <module> 
  3. ValueError: invalid literal for int() with base 10: 'one' 

 

责任编辑:华轩 来源: 今日头条
相关推荐

2024-02-19 15:38:08

JsonPython字符串

2024-01-04 09:17:03

前端开发CSV 格式JSON 字符串

2009-06-05 11:16:58

字符串动态转换

2009-11-25 16:55:45

PHP函数explod

2016-12-30 13:16:51

字符串算法代码

2009-07-15 16:56:59

Jython类型Java类型

2024-03-12 07:35:39

Python字符串列表

2021-08-26 09:46:22

JavaScript字符串URL

2017-05-25 15:14:36

2020-12-17 08:08:15

CentOS

2021-11-29 00:17:41

JS符串转换

2021-11-29 08:49:37

字符串转换整数

2009-07-31 14:09:41

c#时间格式转换

2009-12-01 14:00:37

PHP字符串转换为数值

2022-09-22 11:40:11

JavaScript数组开发

2023-10-16 09:26:48

CSS类型转换

2010-11-26 14:09:32

MySQL内置函数

2010-03-31 19:15:25

Oracle函数

2011-04-08 10:16:13

文本文件ACCESS数据库

2021-08-20 06:58:31

C++Python函数
点赞
收藏

51CTO技术栈公众号