《Python编程从入门到实践》学习笔记 int()

python3 中的 int() 强制类型转换问题:

input()默认接收到的是字符串类型

 

>>> a = input("input:")

input: 1      #此时a是字符串string

>>> print(int(a))

1    #强制转换为整数

但:

>>> a = input("input:")

input: 1.5      #此时a是字符串string

>>> print(int(a))

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

字符串“1.5”无法被强制转换,此时有两种解决办法:

  1. 用 float() 将“1.5”转换为小数
  2. 用 eval(),将字符串str当成有效的表达式来求值并返回计算结果(来源

最后,关于int()的用法,我还没有搞懂base,二进制的换算等内容,先mark一下:

class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
-- More --

posted @ 2020-06-22 20:43  恒宇杜  阅读(153)  评论(0)    收藏  举报