python中,如何将字符串转换为数字(将数字转换为整型),字符串的10转换为整型的10,10.5转换为10

时间:2023-03-09 23:13:16
python中,如何将字符串转换为数字(将数字转换为整型),字符串的10转换为整型的10,10.5转换为10

说明

  在实际的应用过程中,有的时候可能会遇到字符串的10,需要将字符串的10转换为数字的10

  在此记录下,通过int函数转换的过程。

操作过程

1.将字符串转换为整型的10

>>> str1 = ""        #将一个字符串的10赋给变量str1
>>> type(str1)
<class 'str'> #通过type函数查出来类型是str
>>> int1 = int(str1) #通过int函数,转换为了int类型的10
>>> type(int1)
<class 'int'>
>>> int1
10

2.如果不传任何的参数,int的结果是0

>>> int()
0

3.如果传入的是小数,转换的结果是没有小数部分

>>> int(10.0)
10
>>> int(10.5)
10
>>> int(-10.5)
-10
>>> int(-10.0)
-10

备注:无论传入的正数,还是负数,都会将小数部分去掉,符号保留。

int()函数的官方解释

    def __init__(self, x, base=10): # known special case of int.__init__
"""
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
# (copied from class doc)
"""
pass

文档创建时间:2018年12月7日16:53:32