python学习记录
《Python编程:从入门到实践》笔记
(第一次写博客)
python之禅
# ------------------python之禅------------------
# 可以通过import this来输出python之禅
import this
python字符串
# ------------------字符串------------------
# 字符串单词首字母大写,全部大写,全部小写
name = "ada loveface"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "loveface"
full_name = first_name + " " + last_name
print("Hello," + full_name.title() + "!")
# lstrip, rstrip, strip, 三个清除空白的函数
favorite_language = " python "
print(favorite_language + "**")
print("**" + favorite_language.rstrip() + "**")
print("**" + favorite_language.lstrip() + "**")
# str()转换成字符串
age = 23
# print("Happy" + age + "rd birthday!")
print("Happy " + str(age) + "rd birthday!")
数学运算
# ------------------数学运算------------------
# 常用运算: +, -, *, /, **
# 注意,python3不必担心整数除法的结果
print(3 / 2)
python列表
- 定义与访问
# ------------------列表的定义与访问------------------
bicycles = ["trek", "cannondale", "redline", "specialized"]
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
# 下表访问,从0开始
print(bicycles[1])
# 复数表示倒数第几个元素
print(bicycles[-1])
- 增删改
# ------------------列表的增删改------------------
# 改变列表元素
motorcycles = ["honda", "yamaha", "suzuki"]
print(motorcycles)
motorcycles[0] = "ducati"
print(motorcycles)
# 添加元素 append
motorcycles.append("honda")
print(motorcycles)
# 添加元素 insert 按索引添加
motorcycles.insert(0, "new")
print(motorcycles)
# 删除元素 del 按索引删除
del motorcycles[0]
print(motorcycles) # ['ducati', 'yamaha', 'suzuki', 'honda']
del motorcycles[1]
print(motorcycles) # ['ducati', 'suzuki', 'honda']
# 删除元素 pop 删除元素,并作为pop的返回值返回
# 默认尾元素,也可以指定下标
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
motorcycles.append(popped_motorcycle) # ['ducati', 'suzuki', 'honda']
popped_motorcycle = motorcycles.pop(1)
print(motorcycles, popped_motorcycle) # ['ducati', 'honda'] suzuki
# 删除元素 remove 按值删除
motorcycles = ['ducati', 'yamaha', 'suzuki', 'honda']
motorcycles.remove("suzuki")
print(motorcycles) # ['ducati', 'yamaha', 'honda']
too_expensive = "ducati"
motorcycles.remove(too_expensive)
print(motorcycles) # ['yamaha', 'honda']