zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    存储过程参数传递
    iCkeck插件
    单点登录
    SQL数据库默认实例与命名实例的区别
    IE浏览器重复提交ajax请求有缓存
    IE里Iframe的Cookie问题解决办法总结
    微信公众服务号开发
    解析url参数含有特殊字符的情况
    使用客户端控件展示增删改查操作
    修改网站web.config后出现奇怪问题找不到网页
  • 原文地址:https://www.cnblogs.com/chuanzhang053/p/10083844.html
Copyright © 2011-2022 走看看