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


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

用法示例:

  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' 

评论关闭