Python3数据类型及转换

发布时间:2019-05-17 21:44:00编辑:auto阅读(2058)

    I. 数据类型

    Python3将程序中的任何内容统称为对象(Object),基本的数据类型有数字和字符串等,也可以使用自定义的类(Classes)创建新的类型。

    Python3中有六个标准的数据类型:

    • Number(数字)
    • String(字符串)
    • List(列表)
    • Tuple(元组)
    • Set(集合)
    • Dictionary(字典)

    Python3的六个标准数据类型中:

    • 不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
    • 可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。

    1. Number:int, float, bool, complex

    a, b, c, d = 1, 2.3, True, 4+5j
    print(type(a), type(b), type(c), type(d), type(a+b+c+d), a+b+c+d)

    <class 'int'> <class 'float'> <class 'bool'> <class 'complex'> <class 'complex'> (8.3+5j)

    2. String:

    Python中的字符串用单引号'或双引号"括起来,同时使用反斜杠\转义特殊字符。r或R表示原始字符串。

    s = r'this is raw string \n \t.'
    print(type(s), s)

    <class 'str'> this is raw string \n \t.

    3. List:

    列表是写在方括号[]之间,用逗号分隔开的元素列表。列表的元素可以是数字、字符串和列表。

    4. Tuple: 

    元组是写在小括号()之间,用逗号分隔开的元素列表。

    t = (1, 2.3, True, 4+5j, (6, 'abc', ['d', {'id': 9, 'value': 'dict'}]))
    print(type(t), t)

    <class 'tuple'> (1, 2.3, True, (4+5j), (6, 'abc', ['d', {'id': 9, 'value': 'dict'}]))

    5. Set:

    集合可以使用{}或set()函数来创建,创建空集合必须用set()。

    基本功能是测试成员关系和删除重复元素。

    s1 = {1.2, 4+5j, 'abc', 'abc', 'd'}
    s2 = set('abcdde')
    print(type(s1), s1, type(s2), s2)
    print(s1 - s2, s1 | s2, s1 & s2, s1 ^ s2)

    <class 'set'> {1.2, (4+5j), 'd', 'abc'} <class 'set'> {'c', 'a', 'd', 'e', 'b'}
    {1.2, (4+5j), 'abc'} {1.2, 'c', 'a', 'd', (4+5j), 'abc', 'e', 'b'} {'d'} {'c', 1.2, 'a', (4+5j), 'abc', 'e', 'b'}

    6. Dictionary:

    字典通过{}或dict()函数创建,是无序的key:value映射的集合。key必须为不可变类型且唯一。

    d1 = {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}, (True, 4+5j): [1, 'abc']}
    d2 = dict([(1, 'abc'), ('name', {'cn': 'Chinese name', 'en': 'English name'})])
    d3 = dict(name={'cn': 'Chinese name', 'en': 'English name'}, one='abc')
    print(type(d1), d1, d1[(True, 4+5j)])
    print(type(d2), d2, d2[1])
    print(type(d3), d3, d3['one'])

    <class 'dict'> {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}, (True, (4+5j)): [1, 'abc']} [1, 'abc']
    <class 'dict'> {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}} abc
    <class 'dict'> {'name': {'cn': 'Chinese name', 'en': 'English name'}, 'one': 'abc'} abc

    II.数据类型转换

     

    参考:简明Python教程(英文原版)、菜鸟教程

             数据类型转换字符串转字典

关键字