本文内容来自于《Python编程从入门到实践》总结,该书内容简单,对于有编程基础的同学很容易上手,很多语法和js很像,比如arr.pop(),str.strip()等这些都是前端js里有的方法,课后题也很简单,都是对其章节所教的语法的一个使用,对python感兴趣的同学可以从这本书学起。
字符串操作
str.title() #首字母大写
str.upper() #全部大写
str.lower() #全部小写
str.rstrip() #去掉后面的空格
str.lstrip() #去掉前面的空格
str.strip() #去掉前后的空格
str() #转换成字符串
str+str #字符串拼接
str.split() #字符串转数组
列表(就是数组)操作:
arr.append() #从末尾添加元素
arr.insert(index,data) #指定索引添加元素
del arr[index] #删除指定索引元素
arr.pop() #删除列表末尾的元素,返回被删除的元素
arr.pop(index) #删除指定索引
arr.remove('data') #根据值删除,如果有多个,只删除第一个
arr.sort() #永久性排序
arr.sort(reverse = True) #永久性反向排序
arr.sorted() #临时排序
arr.sorted(reverse = True) #临时倒序排序
arr.reverse() #永久性倒序排序
len(arr) #获取列表长度
遍历:缩进和 : 非常重要!
for item in arr:
print(item)
#生成一系列数字range()
#包含第一个值,不包含第二个值
for value in range(1,5):
print(value)
#创建数字列表list()
arr = list(range(1,6))
#从2开始。不断+2,直到达到或超过终值11
arr = list(range(2,11,2))
min(arr) #找数字列表最小值
max(arr) #找数字列表最大值
sum(arr) #数字列表总和
列表切片:
字符串截取切片一样的
#包含第一个值,不包含第二个
arr[0:3] #截取0,1,2的元素,返回新列表
arr[:4] #没指定第一个索引,自动从头开始
arr[2:] #没指定第二个索引,截取到列表末尾
arr[-3:] #从右边开始,倒数第三个
遍历切片:
for item in arr[:3]:
print(item)
复制列表:
arr = arr1[:]
元组:不可变的列表称为元组,元组可重新赋值
if用法:
条件语句可包含各种数学比较,< , <= , > , >=
检查多个条件用 and 连接,或者or(至少有一个满足),相当于 && 和 ||
for car in cars:
if car == 'bmw':
print('have bmw')
if-elif-else car == 'benchi' or car == 'luhu':
print('have benchi or luhu')
else:
print('not')
#检查列表中是否包含特定的值:
item in arr #值为True/False
item not in arr #不包含,值为True/False
字典(就是对象):
obj = {
'color': 'green',
'point': 5
}
obj['color'] #获取值
obj['new'] = 2 #添加
obj = {} #使obj置空
obj['new'] = 1 #修改
del obj['new'] #永久删除
遍历字典:
for key,value in obj():
print(key,value)
#遍历所有键
for name in obj.keys():
#或者
for name in obj:
#遍历字典时,会默认遍历所有的键
#按照特定的顺序:
for name in sorted(obj.keys()):
#遍历所有的值:
for name in obj.values():
#遍历不重复的值:
for k in set(obj.values()):
while循环
num = 1
while num <= 5
print(num)
num += 1
#输出:
# 1
# 2
# 3
# 4
# 5
让用户选择何时退出
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
message = ""
while message != 'quit':
message = input(prompt) #input()获取用户输入
print(message)
#结果
#Tell me something,and I will repeat it back to you:
#Enter 'quit' to end the program. Hello
#Hello
#Tell me something,and I will repeat it back to you:
#Enter 'quit' to end the program. Hello again
#Hello again
#Tell me something,and I will repeat it back to you:
#Enter 'quit' to end the program. quit
#quit
#结束
使用标志
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
#结果与上面一致,当输入'quit'时结束程序
使用break退出循环
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
while True:
message = input(prompt)
if message == 'quit':
break
else:
print(message)
#结果与上面一致,当输入'quit'时结束程序
函数
def user():
print('hello')
user() #hello
函数传参
def user(name):
print('hello ' + name)
user('xiaoming') #hello xiaoming
函数返回值
def user(name):
str = 'hello ' + name
return str
getName = user('xiaoming')
print(getName) #hello xiaoming
文件
读取文件
with open('file.txt') as file:
contents = file.read()
print(contents.rstrip())
#一行一行读取文件
with open('file.txt') as line_file:
for line in line_file
print(line.rstrip())
#读取每一行然后存储在一个列表中,可在with代码块外部访问
filePath = 'file.txt'
with open(filePath) as readlines_file:
lines = readlines_file.readlines()
for line in lines:
print(line.rstrip())
read() 到达文件末尾时会返回一个空字符串,所以使用 rstrip()
Linux 和 OS X 中文件路径用 ’/‘,windows用 ’\‘
注:python将所有文本都解读为字符串,如果你读取的是数字,并将其当坐数值使用,就必须使用 int() 或 float()
写入文件
with open ('filepath', 'w') as files:
files.write('你写入的内容')
#写入多行,使用 \n
with open ('filepath', 'w') as files:
files.write('你写入的第一行内容\n')
files.write('你写入的第二行内容\n')
第二个实参 ’w‘ 的意思是以写入模式打开这个文件
读取模式(默认):’r‘
写入模式:’w‘
附加模式:’a‘
读取和写入:’rt‘
注:写入模式时,如果没有该文件,函open()会自动创建,如果已经存在该文件,python将在返回文件对象前清空该文件。如果不想覆盖文件原内容,可使用附加模式