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


    说明

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

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

    操作过程

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

    >>> str1 = "10"        #将一个字符串的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

  • 相关阅读:
    JS重写alert,保证弹窗错误的友好性
    wpf窗体中复合控件焦点控制
    mybatis特殊字符转义
    SpringMVC HandlerMethodArgumentResolver自定义参数转换器
    IntelliJ IDEA创建maven web项目
    shiro app
    Linux查看日志定位问题
    Flask中使用Flask-Migrate扩展迁移数据库
    flask + pymysql操作Mysql数据库
    HTTP
  • 原文地址:https://www.cnblogs.com/chuanzhang053/p/10083844.html
Copyright © 2020-2023  润新知