zoukankan      html  css  js  c++  java
  • Python 3 学习笔记之——数据类型

    1. 数字

    类型

    • int, float, bool, complex
    • type() 查看变量类型
    • isinstance(a, int) 查看变量类型

    运算符

    • % 取余
    • // 返回商的整数部分
    • ** 幂
    • & 按位与
    • | 按位或
    • ^ 按位异或
    • ~ 按位非
    • and 逻辑与
    • or 逻辑或
    • not 逻辑非
    • in、not in 成员运算符
    • is、is not 判断两个对象是否引用自一个对象
    • id() 用于获取对象内存地址

    2. 字符串

    a = 'hello'
    b = 'seniusen'
    a + b # 字符串拼接 'helloseniusen'
    a * 2 # 重复输出字符串 'hellohello'
    
    # 字符串格式化输出
    print(repr(3).rjust(2), repr(16).rjust(3)) # 靠右对齐,ljust()、center() 靠左、居中对齐
    print('12'.zfill(5)) # '000123',在数字的左边填充 0
    
    print('My name is %s, my lucky number is %d.' %('seniusen', 3))
    print('My name is {}, my lucky number is {}.'.format('seniusen', 3)) 
    # My name is seniusen, my lucky number is 3.
    
    print('站点列表 {0}, {1}, 和 {other}。'.format('Google', 'Runoob', other='Taobao'))
    # 站点列表 Google, Runoob, 和 Taobao。
    
    
    print('常量 PI 的值近似为:%5.3f。' % 3.1415926)
    print('常量 PI 的值近似为:{0:5.3f}。'.format(3.1415926))
    # 在 ':' 后传入一个整数, 可以保证该域至少有这么多的宽度, .3 表示浮点数保留 3 位小数
    
    print('常量 PI 的值近似为: {!r}。'.format(3.1415926)) # 相当于 repr()
    print('常量 PI 的值近似为: {!s}。'.format(3.1415926)) # 相当于 str()
    

    3. 元组

    a = () # 新建一个空元组
    a = (2, ) # 新建一个只有一个元素的元组
    a = (2) # 此时 a 为 int 类型
    (1, 2, 3) + (4, 5, 6) # (1, 2, 3, 4, 5, 6)
    (1, 2, 3) * 2 # (1, 2, 3, 1, 2, 3)
    

    4. 列表

    5. 字典

    a = {} # 新建一个空字典
    
    >>> a = {'name':'seniusen', 'age':21}
    >>> a.keys() # 字典的键
    dict_keys(['name', 'age'])
    >>> a.values() # 字典的值
    dict_values(['seniusen', 21])
    >>> a.items() # 字典的项
    dict_items([('name', 'seniusen'), ('age', 21)])
    >>> list(a.keys())
    ['name', 'age']
    
    

    6. 集合

    a = set() # 新建一个空集合
    
    >>> b = set('defgh')
    >>> b
    {'e', 'h', 'd', 'f', 'g'}
    >>> a = set('abcde')
    >>> a
    {'a', 'b', 'd', 'c', 'e'}
    >>> a - b # 只在 a 中不在 b 中的元素
    {'a', 'b', 'c'}
    
    >>> a & b # 既在 a 中又在 b 中的元素,交集
    {'e', 'd'}
    >>> a | b # 在 a 和 b 中的所有的元素,并集
    {'b', 'g', 'h', 'f', 'c', 'd', 'a', 'e'}
    >>> a ^ b # 只在 a 中或只在 b 中的元素
    {'b', 'g', 'h', 'f', 'c', 'a'}
    
    

    7. 数据类型之间的转换

    参考资料 菜鸟教程

    获取更多精彩,请关注「seniusen」!

  • 相关阅读:
    登录验证并记录日志
    Java基础——单列
    web下载文件和跳转
    关于乱码问题的解决与HttpServletResponse中的方法
    request和response中的方法使用
    JavaEE——Servlet的Web访问名称
    JavaEE——HttpServletRequest对象
    三元表达式执行顺序 逻辑运算符的运用
    《Java多线程编程实战指南+设计模式篇》笔记
    java -jar jar包,运行报错没有主清单和无法加载主类
  • 原文地址:https://www.cnblogs.com/seniusen/p/9843695.html
Copyright © 2011-2022 走看看