一、 Python3 中有六个标准的数据类型:
Number(数字)、String(字符串)、List(列表)、Tuple(元组)、Set(集合)、Dictionary(字典)
1,数字
a, b, c, d = 10, 1.5, True, 1+2j
print(type(a), type(b), type(c), type(d))
2,字符串
# 读取方式:下标索引和切片
a = 'Hello'
b = "World"
print ("a[0]: ", a[0])
print ("b[1:5]: ", b[1:5])
# 使用 + 连接字符串
print(a + b)
# 使用 * 重复字符串
print(a * 3)
使用反斜杠(\)转义特殊字符,如果你不想让反斜杠发生转义,可以在字符串前面添加一个 r,表示原始字符串。
print('Ru\noob')
print(r'Ru\noob')
字符串格式化
它通过{}和:来代替传统%方式
1,使用位置参数
li = ['hoho',18]
print('my name is {} ,age {}'.format('hoho',18))
2,使用关键值参数
hash = {'name':'hoho','age':18}
print('my name is {name},age is {age}'.format(name='hoho',age=19))
hash = {'name':'hoho','age':18}
print('my name is {name},age is {age}'.format(**hash))
3,列表
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
访问列表中的值
list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7];
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])
list = ['Google', 'Runoob', 1997, 2000]
print("原始列表 : ", list)
del list[2]
print("删除第三个元素 : ", list)
4,元组
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
# 创建一个新的元组
tup3 = tup1 + tup2
print(tup3)
tup = ('physics', 'chemistry', 1997, 2000)
print(tup)
del tup
"After deleting tup : "
print(tup)
5,集合
集合(set)是一个无序的不重复元素序列。
可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
创建格式:
parame = {value01,value02,...}
或者
set(value)
a = set('abracadabra')
print(a)
集合的基本操作
添加元素.add()
thisset = set(("Google", "Runoob", "Taobao"))
thisset.add("Facebook")
print(thisset)
还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等,语法格式如下:
s.update( x )
thisset = set(("Google", "Runoob", "Taobao"))
thisset.update({1,3})
print(thisset)
thisset.update([1,4],[5,6])
print(thisset)
移除元素 s.remove( x )
thisset = set(("Google", "Runoob", "Taobao"))
thisset.remove("Taobao")
print(thisset)
清空集合
s.clear()
thisset = set(("Google", "Runoob", "Taobao"))
thisset.clear()
print(thisset)
6,字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age'])
修改字典
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # 更新 Age
dict['School'] = "菜鸟教程" # 添加信息
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])