一:变量和简单的数据类型
二:列表
注意:运行环境centos7.5, python3.6
一:变量和简单的数据类型
1:注释
#后面加注释语句
#这是一个注释
2:变量
python中的类型不像c/c++中那样需要明确指出,只需要给出一个变量,它就可以推导出类型;类似于c++中的auto关键字
a = 666 #整型
b = 3.1415926 #浮点数
str1 = 'belongal' #字符串
str2 = "belongal" #字符串
需要说明的是,python可以使用'' 和 ""来标记字符串,这就使得我们在字符串中添加“和‘容易:eg:
str1 = 'belo"ngal'
str2 = "belo'ngal"
3:输出
eg:
message = "hello world"
print(message)
[root@VM_0_11_centos py]# python test.py
hello world
4:制表符换行符
eg:
hello = "\theLLo\n\tpython\n\tworld"
print(hello)
[root@VM_0_11_centos py]# python test.py
heLLo
python
world
5:几个使用接口介绍
a:更改字符串大小写
eg:
message = "heLLo wOrlD"
print(message)
message = message.lower()#全部小写
print(message.title())#首字母大写
print(message.upper())#全部大写
[root@VM_0_11_centos py]# python test.py
heLLo wOrlD
Hello World
HELLO WORLD
b:合并字符串
eg:
hello = "heLLo python"
world = "world"
print(hello + " " + world)
[root@VM_0_11_centos py]# python test.py
heLLo python world
c:删除空白
eg:
hello = " heLLo python world "
print(hello + "!")
print(hello.rstrip() + "!")#删除后面多余空白
print(hello.lstrip() + "!")#删除前面多余空白
print(hello.strip() + "!")#删除前后
[root@VM_0_11_centos py]# python test.py
heLLo python world !
heLLo python world!
heLLo python world !
heLLo python world!
d:数字转字符串
eg:
a = 600
str1 = "i have "
str2 = " yuan"
#print(str1 + a + str2)出错
print(str1 + str(a) + str2)
[root@VM_0_11_centos py]# python test.py
i have 600 yuan
二:列表
1:列表介绍
eg:
arr = [1,2,3,4,5,6]
print(arr)#打印整个列表
print(arr[0])#打印具体元素
[1, 2, 3, 4, 5, 6]
1
2:列表增删查改
eg:
arr = [1,2,3,4,5,6]
print(arr)#打印整个列表
#修改
arr[2] = 888;
print(arr)
#添加
arr.append(666)#末尾追加
print(arr)
arr.insert(2, 999)#在第三个的位置插入
print(arr)
#删除
del arr[1]#删除1号元素
print(arr)
tmp = arr.pop()#弹出最后一个元素
print(arr)
print(tmp)
tmp = arr.pop(3)#弹出3号位置的元素
print(arr)
print(tmp)
arr.remove(5)#根据值删除元素
print(arr)
[1, 2, 3, 4, 5, 6]
[1, 2, 888, 4, 5, 6]
[1, 2, 888, 4, 5, 6, 666]
[1, 2, 999, 888, 4, 5, 6, 666]
[1, 999, 888, 4, 5, 6, 666]
[1, 999, 888, 4, 5, 6]
666
[1, 999, 888, 5, 6]
4
[1, 999, 888, 6]
3:组织列表
排序 && 逆序 && 获取大小
eg:
arr = [2,56,1236,12,9,13,67,8]
#持久性排序
print(arr)#打印整个列表
arr.sort()#正序排序
print(arr)
arr.sort(reverse=True)#传递参数,使得列表逆序排序
print(arr)
#临时排序
arr = [2,56,1236,12,9,13,67,8]
print(sorted(arr))
print(sorted(arr, reverse=True))
print(arr)
#倒着打印列表
print(arr)
arr.reverse()
print(arr)
#获取列表长度
print(len(arr))
[2, 56, 1236, 12, 9, 13, 67, 8]
[2, 8, 9, 12, 13, 56, 67, 1236]
[1236, 67, 56, 13, 12, 9, 8, 2]
[2, 8, 9, 12, 13, 56, 67, 1236]
[1236, 67, 56, 13, 12, 9, 8, 2]
[2, 56, 1236, 12, 9, 13, 67, 8]
[2, 56, 1236, 12, 9, 13, 67, 8]
[8, 67, 13, 9, 12, 1236, 56, 2]
8