常用数据类型及操作
简介
最近在学习python,了解一下智能语言的使用及脚本开发,在此做记录方便后期巩固和回溯,个人感觉python的语法和结构与Lua很相似
数据类型
- Number :数值类型(不可变数据),包含:int,float,bool,complex(复数)
- String :字符串类型(不可变数据),使用单引号''或双引号""都可以
- bool : 布尔类型
- List : 列表(可变数据)
- Tuple : 元组(不可变数据)
- Set :集合(可变数据)
- Dictionary :字典(可变数据)
- bytes :二进制
声明或使用
声明
python语法中,声明变量不需要加入变量类型,并且在被赋值后才会创建变量对象,例如:
test1 = "Asd" #声明test1变量为字符串
test2 = 1 #声明test2变量为数值类型
test3 = True #声明变量test3为bool类型,python3中,bool是int的子类型,True==1,False==0
test4 = ['abcd',1,2,30.1] #声明变量test4为列表类型
test5 = ('abcd',1,71.1) #声明变量test5为元组类型,当声明只包含一个元素的元组时,需要在元素后面加入逗号:test=(1,)
test6 = {"asd","bcs"} #声明变量test6为集合类型,当声明空集合时需要使用set(),例如:test=set()
test7 = {'name':'runoob','code':1} #声明test7为字典类型
test8 = bytes("hello",encoding="utf-8") #声明变量test8为bytes类型
def testFunc(): #声明变量testFunc为函数
return;
使用
1. 字符串
字符截取
Python 使用反斜杠 \ 转义特殊字符,如果你不想让反斜杠发生转义,可以在字符串前面添加一个 r,表示原始字符串
- 反斜杠可以用来转义,使用r可以让反斜杠不发生转义。
- 字符串可以用+运算符连接在一起,用*运算符重复。
- Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始。
- Python中的字符串不能改变。
str = 'Runoob' # 定义一个字符串变量
print(str) # 打印整个字符串
print(str[0:-1]) # 打印字符串第一个到倒数第二个字符(不包含倒数第一个字符)
print(str[0]) # 打印字符串的第一个字符
print(str[2:5]) # 打印字符串第三到第五个字符(不包含索引为 5 的字符)
print(str[2:]) # 打印字符串从第三个字符开始到末尾
print(str * 2) # 打印字符串两次
print('Ru\nnob')
print(r'Ru\nnob')
格式化
- 常用格式化方式与C语言的格式化大致相似,都是使用%s、%d等
- f-string格式化,类似于C#中的$(python3.6之后才可使用)
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
test = {"list":[1,2,3,4]}
print(type(test))
for k,v in test.items():
print(f"K:{k} V:{v}")
2. 字典、列表、元组、集合
#字典,可以使用for循环,但是需要注意会返回key和value,所以需要两个变量去接收
test = {"list":[1,2,3,4]} #字典
print(type(test)) #输出:<class 'dict'>
test1 = test
test2 = test.copy()
del test2["list"]
print(test) #输出:{'list': [1, 2, 3, 4]}
print(test1) #输出:{'list': [1, 2, 3, 4]}
print(test2) #输出:{}
#列表,可以使用for循环
test = [1,2,3,"aasd"]
print(type(test)) #输出:<class 'list'>
test1 = test
test2 = test.copy()
del test2[2]
print(test) #输出:[1, 2, 'aasd']
print(test1) #输出:[1, 2, 'aasd']
print(test2) #输出:[1, 2, 3, 'aasd']
#元组,不支持修改元素,但是元素中如果包含列表或字典可以修改列表或字典里的值,可以使用for循环
test = ("a","b",3,4,8)
print(type(test)) #输出:<class 'tuple'>
print(test) #输出:('a', 'b', 3, 4, 8)
#集合,没有索引不能通过索引值获取内容,可以使用for循环,集合的创建与字典类似,但是需要注意空集合创建要用set(),'{}'是空字典
test = {"aabb","asdcd"}
print(type(test)) #输出:<class 'set'>
test1 = test
test2 = test.copy()
test.add("abcd")
test2.update("hhh")
test1.remove("asdcd")
test2.discard("acd")
print(test) #输出:{'aabb', 'abcd'}
print(test1) #输出:{'aabb', 'abcd'}
print(test2) #输出:{'asdcd', 'aabb', 'hhh'}