zoukankan      html  css  js  c++  java
  • python之 数据类型判定与类型转换


    一、 判断数据类型

    0、type(x)
    type()可以接收任何东西作为参数――并返回它的数据类型。整型、字符串、列表、字典、元组、函数、类、模块,甚至类型对象都可以作为参数被 type 函数接受。

    >>> type(1)
    <type 'int'>
    >>> li = []
    >>> type(li)
    <type 'list'>
    >>> import odbchelper
    >>> type(odbchelper)
    <type 'module'>
    >>> import types
    >>> type(odbchelper) == types.ModuleType
    True

    二、 数据类型转换

    1、chr(i)
    chr()函数返回ASCII码对应的字符串。

    >>> print chr(65)
    A
    >>> print chr(66)

    >>> print chr(65)+chr(66)
    AB

    2、complex(real[,imaginary])
    complex()函数可把字符串或数字转换为复数。


    >>> complex("2+1j")
    (2+1j)
    >>> complex("2")
    (2+0j)
    >>> complex(2,1)
    (2+1j)
    >>> complex(2L,1)
    (2+1j)

    3、float(x)
    float()函数把一个数字或字符串转换成浮点数。

    >>> float("12")
    12.0
    >>> float(12L)
    12.0
    >>> float(12.2)
    12.199999999999999

    4、hex(x)
    hex()函数可把整数转换成十六进制数。

    >>> hex(16)
    '0x10'
    >>> hex(123)
    '0x7b'

    5、long(x[,base])
    long()函数把数字和字符串转换成长整数,base为可选的基数。

    >>> long("123")
    123L
    >>> long(11)
    11L

    6、list(x)
    list()函数可将序列对象转换成列表。如:

    >>> list("hello world")
    ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
    >>> list((1,2,3,4))
    [1, 2, 3, 4]

    7、int(x[,base])
    int()函数把数字和字符串转换成一个整数,base为可选的基数。

    >>> int(3.3)
    3
    >>> int(3L)
    3
    >>> int("13")
    13
    >>> int("14",15)
    19

    8、min(x[,y,z...])
    min()函数返回给定参数的最小值,参数可以为序列。

    >>> min(1,2,3,4)
    1
    >>> min((1,2,3),(2,3,4))
    (1, 2, 3)

    9、max(x[,y,z...])
    max()函数返回给定参数的最大值,参数可以为序列。

    >>> max(1,2,3,4)
    4
    >>> max((1,2,3),(2,3,4))
    (2, 3, 4)

    10、oct(x)
    oct()函数可把给出的整数转换成八进制数。

    >>> oct(8)
    '010'
    >>> oct(123)
    '0173'

    11、ord(x)
    ord()函数返回一个字符串参数的ASCII码或Unicode值。

    >>> ord("a")
    97
    >>> ord(u"a")
    97

    12、str(obj)
    str()函数把对象转换成可打印字符串。

    >>> str("4")
    '4'
    >>> str(4)
    '4'
    >>> str(3+2j)
    '(3+2j)'

    13、tuple(x)
    tuple()函数把序列对象转换成tuple。

    >>> tuple("hello world")
    ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
    >>> tuple([1,2,3,4])
    (1, 2, 3, 4)

  • 相关阅读:
    SE知识整理——泛型
    IDEA 运行 SpringMVC 项目分发控制器出现404解决方案。
    快速幂/欧拉降幂
    Leetcode(双指针专题)
    剑指offer
    ns3参考
    网络知识1:最后一公里/WiMax / 4G
    备份2
    shell入门
    ns3_gdb:协议里的函数是怎么被调用的
  • 原文地址:https://www.cnblogs.com/andy6/p/8017590.html
Copyright © 2011-2022 走看看