python的一些小技巧

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)
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"

Python序列解包

# 将name中的姓和名单独提取出来
# [1]
name = "San Zhang"
str_list = name.split()
print(str_list)
# [2]
name = "San Zhang"
first_name, last_name = name.split()
print(first_name,last_name)

Python with语句

#例:用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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值