name = "John"
age = 20
# % 方式
print("My name is %s,I am %s", % (name,age))
# format 函数
content = "My name is {},I am {}".format(name, age)
print(content)
# format 函数用索引占位
name = "John"
content = "My name is {0},I am {0}".format(name)
print(content)
# f-strings
print(f"My name is{name},I am {age}")
# 数字处理输出
print("圆周率:{:.2f}".format(3.1415926)) # :表示对format的内容就行操作,.2f表示保留两位小数
print("{:,}".format(100000000)) # 千分位加逗号,格式化
print("{:.2e}".format(100000000)) # 科学计数法, .2表示保留小数点后面两位
print("{:.1%}".format(0.25)) # 百分号表示, .1表示保留一位小数
Python循环列表
# 例1:遍历content元祖的元素并全部置为大写
# [1]
content = ["John", "18", "Chengdu"]
for x in range(len(content)):
content[x] = content[x].upper()
print(content)
# [2]
content = ["John", "18", "Chengdu"]
content = [x.upper() for x in content]
print(content)
#例2:找出fruit元祖中以'a'开始的元素
# [1]
fruit = ["apple", "pear", "pineapple", "orange"]
filtered_fruit = []
for f in fruit:
if f.startswith("a"):
filtered_fruit.append(f)
print(filtered_fruit)
# [2]
fruit = ["apple", "pear", "pineapple", "orange"]
filtered_fruit = [f for f in fruit if f.startswith("a")]
print(filtered_fruit)
#例3:遍历元祖fruit,并输出每个元素的索引
fruit = ["apple", "pear", "pineapple", "orange"]
for x, y in enumerate(fruit):
print(x, y)
#例4:反向遍历元祖fruit,并输出每个元素的索引
fruit = ["apple", "pear", "pineapple", "orange"]
for x, y in enumerate(reversed(fruit)):
print(x, y)
#例5:遍历元组fruit并排序输出
fruit = ["apple", "pear", "pineapple", "orange"]
for x, y in enumerate(sorted(fruit)):
print(x, y)
Python合并字典
#将a和b合并
#[1]
a = {"souther": "123", "rose": "abc"}
b = {"fly": "321", "dance": "cba"}
c = {}
for k in a:
c[k] = a[k]
for k in b:
c[k] = b[k]
#[2]
# c = {**a,**b},解包a和b,相当于把a和b内容填入c
a = {"souther": "123", "rose": "abc"}
b = {"fly": "321", "dance": "cba"}
c = {**a, **b}
print(c)
Python三元运算符
#例:输入score,若score大于60,则pass,否则fali
# [1]
score = int(input("请输入分数: "))
if score > 60:
s = "pass"
else:
s = "fail"
print(s)
# [2]
score = int(input("请输入分数: "))
s = "pass" if score > 60 else "fail"
#例:用open方法打开一个文件
# [1]
f = open("text.txt", "r")
s = f.read()
f.close()
print(s)
# [2]
# 用with语句就不需要在后面再使用close()了
with open("text.txt", "r") as f:
s = f.read()
print(s)
Python学习Python常见输出方式name = "John"age = 20# % 方式print("My name is %s,I am %s", % (name,age))# format 函数content = "My name is {},I am {}".format(name, age)print(content)# format 函数用索引占位name = "John"content = "My name is {0},I am {0}".format(name)