iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python3数据类型及转换
  • 140
分享到

Python3数据类型及转换

数据类型 2023-01-30 23:01:45 140人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

I. 数据类型 python3将程序中的任何内容统称为对象(Object),基本的数据类型有数字和字符串等,也可以使用自定义的类(Classes)创建新的类型。 python3中有六个标准的数据类型: Number(数字) String

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教程(英文原版)、菜鸟教程

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

--结束END--

本文标题: Python3数据类型及转换

本文链接: https://www.lsjlt.com/news/181335.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作