Today, I saw an article suitable for beginners to refer to on today's headlines, and I especially introduced it here. See the original link and author at the end of the article.
Swap the value of the variable
a, b, c = 10, 20, 30
print(a, b, c)
a, b, c = b, c, a
print(a, b, c)
Output result:
10 20 30
20 30 10
chain comparison
score = 75
if 70 <= score < 80:
print('成绩:良')
Quickly merge dictionaries
dict1 = {
'数学': 90, '语文': 98, '英语': 93}
dict2 = {
'地理': 78, '化学': 70}
dict3 = dict1 | dict2
print(dict3)
Output result:
{'Mathematics': 90, 'Chinese': 98, 'English': 93, 'Geography': 78, 'Chemistry': 70}
header combines two lists into a dictionary
key = ['数学', '语文', '英语']
value = [90, 99, 87]
result = dict(zip(key, value))
print(result)
Output result:
{'Mathematics': 90, 'Chinese': 99, 'English': 87}
Randomly sort list elements (shuffling effect)
import random
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
random.shuffle(lst)
print(lst)
Output result:
[2, 7, 4, 6, 3, 8, 5, 1, 0, 9]
Select a specified number of random and non-repeating elements from the list (lottery effect)
import random
lst = ['z', 'b', 'Ab', 'CDE', '5', 6, 100, True, 3.14]
result = random.sample(lst, 3)
print(result)
Output result:
[6, 'z', 'CDE']
Randomly select an element or character from a list or string (can be used to generate captchas or dynamic passwords)
import random
str1 = '0123456789abcdefghijklmnopqtstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()'
result=''
for i in range(8):
result = result+random.choice(str1)
print(result)
Output result:
ZItOAZyC
Voice read text
import winsound
import win32com
from win32com.client import Dispatch, constants
import time
speak_out = win32com.client.Dispatch('sapi.spvoice')
str='今天的气温是'+' '+'零下19度'
speak_out.speak(str) # 输出方言解释
winsound.PlaySound(str, winsound.SND_ASYNC) # 输出结束音
time.sleep(3) # 不加延迟程序马上结束,上面语句的结束音出不来
Computes the difference between two datetimes
import datetime
day1 = datetime.datetime(2022, 7, 17)
day2 = datetime.datetime(2022, 10, 8)
print(f'{day1.strftime("%Y-%m-%d")}与{day2.strftime("%Y-%m-%d")}相隔了' + str((day2 - day1).days) + '天!')
Output result:
83 days between 2022-07-17 and 2022-10-08!
Quickly convert Arabic numerals to Chinese numerals
info = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
data = input("请输入数字:")
for i in range(len(data)):
print(info[int(data[i])], end='')
Output result:
Please enter the number:
36983698
else is used with for and while (if the loop is executed and no break is encountered, else is executed)
for num in range(3):
pwd = input('请输入密码:')
if pwd == '8888':
print('输入的密码正确!')
break
else:
print('输入的密码错误,请重新输入!')
else:
print('输入次数达到上限,系统将自动退出!')
buzzer beep
import time, sys, ctypes
'''
time库中包含sleep延迟函数
sys库中包含stdout标准输出刷新函数flush
ctypes库中包含Beep(首字母大写)蜂鸣器,第一个参数是频率,第二个参数是鸣叫时长
'''
player = ctypes.windll.kernel32
for i in range(1, 11):
print('\r', '-●-' * i, end='%d0%%' % i) # \r表示返回行首,在字符串里显示%必须用%%
sys.stdout.flush()
player.Beep(1000, 100)
time.sleep(1)
player.Beep(2000, 1000)
Else and finally for exception handling (if no exception occurs, else is executed, and finally must be executed regardless of whether an exception occurs, even if there is a return statement in front of it)
def func(opr):
result = 0
try:
a = int(input('请输入第一个数:'))
b = int(input('请输入第二个数:'))
if opr == '+':
result = a + b
elif opr == '-':
result = a - b
elif opr == '*':
result = a * b
elif opr == '/':
result = a / b
else:
print('您输入的操作符错误!')
except Exception as err:
print('出错啦!出错信息:', err)
else:
print('运行未发生错误')
return result # 由于有finally语句,这条return语句会在finally下面的语句执行完毕后再执行
finally:
print('-----执行finally语句-----')
r = func('+')
print('返回结果:', r)
Running result:
Please enter the first number: 2
Please enter the second number: 0
No error occurred in the operation
----- execute finally statement -----
return result: 2
The string content is output verbatim
import sys
import time
def repeat(string):
sys.stdout.write("\r") # 回车,让光标回到行首
sys.stdout.flush() # 刷新,即输出缓冲区数据
for i in string: # 遍历字符串
sys.stdout.write(i) # 写到缓冲区
sys.stdout.flush() # 输出
time.sleep(0.3) # 延迟0.3毫秒
while True:
repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
Unify the number of consecutive spaces in a string into one space
word='编号 姓名 性别 年级 学校 奖项'
list=word.split(' ')
listnew=[i for i in list if i!='' ]
new=' '.join(listnew)
print(new)
Output:
ID Name Gender Grade School Awards
Use the list to determine the corresponding constellation of the date (no need to repeatedly determine the month and date range)
def sign(m, d): # 判断星座函数
if d < date[m - 1]: # 如果日期小于该月在date列表中对应的日期临界值
print(sign_list[m - 1]) # 直接输出星座列表中对应月份的星座
else:
print(sign_list[m]) # 否则输出星座列表中下一月对应的星座
date = [20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22] # 每个月份的星座日期临界值
sign_list = ['摩羯座', '水瓶座', '双鱼座', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座',
'天蝎座', '射手座', '摩羯座']
sign(7, 15) # 调用星座判断函数
Output result:
Cancer
Cleverly use the dictionary to judge the ID number information (the character \ is used to connect the upper and lower lines of the statement)
dic = {
'11': '北京市', '12': '天津市', '13': '河北省', '14': '山西省', \
'15': '内蒙古自治区', '22': '吉林省', '23': '黑龙江省', '31': '上海市', \
'32': '江苏省', '33': '浙江省', '35': '福建省', '36': '江西省', '37': '山东省', \
'41': '河南省', '42': '湖北省', '44': '广东省', '45': '广西壮族自治区', \
'46': '海南省', '50': '重庆市', '51': '四川省', '53': '云南省', \
'54': '西藏自治区', '61': '陕西省', '62': '甘肃省', '63': '青海省', \
'65': '新疆维吾尔自治区', '71': '台湾省', '81': '香港', '82': '澳门'}
def idget(str):
if dic.get(str):
return dic[str]
else:
return '未知省份'
instr = input('请输入您的身份证号:')
if instr[:16].isdigit() and len(instr) == 18:
print('你来自:', idget(instr[0:2]))
print('你的生日是:' + instr[6:10] + '年' + instr[10:12] + '月' + instr[12:14] + '日')
gender = '女' if int(instr[16]) % 2 == 0 else '男'
print('你的性别是:' + gender)
Output result:
Please enter your ID number: 220000198308124527
You are from: Jilin Province
Your birthday is: August 12, 1983
Your gender is: Female
Skillfully use random numbers and string slices to complete idiom answering effects
import random
list = ["春暖花开", "十字路口", "千军万马", "白手起家", "张灯结彩", "风和日丽", "万里长城", "人来人往", "自由自在",
"瓜田李下", "助人为乐", "白手起家", "红男绿女", "春风化雨", "马到成功", "拔苗助长", "安居乐业", "走马观花",
"念念不忘", "落花流水", "张灯结彩", "一往无前", "落地生根", "天罗地网", "东山再起", "一事无成", "山清水秀",
"别有洞天", "语重心长", "水深火热", "鸟语花香", "自以为是"]
i = 1
count = 20
print('直接填写答案,回车进入下一关。什么也不填忽略本成语!!')
while True:
word = random.choice(list) # 随机选择成语
bank = random.randint(0, 3) # 随机生成要抹去的字
new = word[:bank] + "___" + word[bank + 1:] # 输出考题
print(new)
num = input("输入:")
if not num: # 如果直接回车则略过此题
print("过!")
continue
elif num.strip(" ") == word[bank]:
count += 2
print("正确,你真棒!")
else:
count -= 2
print("错了,正确答案:", word[bank])
i += 1
if i > 3: # 答题次数
break
print("选手最后得分:", count)
Output result: Fill in the answer directly, and press Enter to enter the next level. Fill in nothing and ignore this idiom! !
Fenghe___Li
Input: Day
Correct, you are awesome!
Go forward without
input:
pass!
Immediate success
Input: gong
Correct, you are awesome!
Feel free to ___
Enter: by
Correct, you are awesome!
Player's final score: 26
Generate product serial number based on date
type_num = "BRM8S"
date = "2021:12:28"
date = date.split(":")
year_num = date[0][2:]
month = hex(int(date[1])).replace("0x", "") # 取月份的十六进制字符
day = date[2]
date_num = year_num + month + day
start = 100
count = int(input("请输入要生成的产品序列号(SN)数量:"))
sn = ""
for i in range(count):
num = type_num + date_num + str(start + i).zfill(5) # 用0填充空位
sn += num + "\n"
print(sn)
Visually display GDP data in the form of a horizontal bar chart
gdp = '广东:97277.77:107671.07 江苏:92595.40:99631.52 ' \
'山东:76469.70:71067.5 浙江:56197.00:62353 河南:48055.90:54259.2 ' \
'四川:40678.10:46615.82 湖北:39366.60:45828.31 湖南:36425.78:39752.12 ' \
'河北:36010.30:35104.5 福建:35804.04:42395'
gdp_dict = {
}
gdp_list = []
base = 3000
new = gdp.split(" ") # 切割列表
for item in new:
gdp_list = item.split(":") # 切割字符串
gdp_dict.update({
gdp_list[0]: [gdp_list[2], gdp_list[1]]}) # 生成字典
up = sorted(gdp_dict.items(), key=lambda x: float(x[1][0]), reverse=False) # 使用匿名函数对字典排序
for item in up:
lenb = format(float(item[1][0]) / base, ".0f") # 计算需要输出的■的个数
print(item[0].ljust(4) + "\t" + int(lenb) * chr(9632) + " 2019年GDP:" + str(item[1][0]))
lenb = format(float(item[1][1]) / base, ".0f")
print("".ljust(4) + "\t" + int(lenb) * chr(9632) + " 2018年GDP:" + str(item[1][1]))
Output results:
Hebei 2019 GDP: 35104.5
2018 GDP: 36010.30
Hunan ■■ 2019 GDP: 39,752.12
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■"■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■"" In 2019 to GDP: 39752.12 ■■■■■■■■■■■■■■■ to over
2018 GDP: 36425.78 ■■■■■■■■■■■■■■■ To 2019 GDP: 42395 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
" ■■■■■■■ 2018 GDP: 35804.04
Hubei■■■■■■■■■■■■■■■■■■ 2019 GDP: 45828.31
■■■■■■■■■■■■■■■■■ 2018 GDP: 39366.60
Sichuan 2019 GDP: 46615.82
2018 GDP: 40678.10
Henan 2019 GDP: 46615.82 ■■■■■■■■■■■ 2019 GDP:54259.2
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■"■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■"■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■"■■■■■■■■■ In 2018: 48055.90
Zhejiang■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ■■■■■■■■■■ 2019 GDP: 62353
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■"■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■"■ In 2018: 56197.00
Shandong■■■■■■■■■■■■■■■■■ 2019 GDP: 71067.5
2018 GDP: 76469.70
Jiangsu ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
" ■■■■■■■■■■■■■■■■■■■■■■ 2018 GDP: 92595.40
Guangdong■■■■■■■■■■■■■■■■■■■■■ 2019 GDP: 107671.07
2018 Annual GDP: 97277.77
Sensitive vocabulary statistics by using the counting function of the number of string substrings
word = input('请输入或者拷贝含有敏感词的宣传文字:\n')
sensitive = ['第一', '国家级', '最高级', '最佳', '独一无二', '一流', '仅此一次', '顶级', '顶尖', '尖端', '极品', '极佳',
'绝佳', '绝对', '终极', '极致', '首个', '首选', '独家', '首发', '首次', '首款', '金牌', '名牌', '王牌',
'领袖', '领先', '领导', '缔造者', '巨星', '掌门人', '至尊', '巅峰', '奢侈', '资深', '之王', '王者', '冠军']
sensitive_find = []
newword = word
for item in sensitive:
if word.count(item) > 0: # 判断敏感词出现的次数
sensitive_find.append(item + ':' + str(word.count(item)) + '次') # 记录敏感词出现次数
newword = newword.replace(item, ' \033[1;31m' + item + '\033[0m') # 敏感词描红输出
print('发现敏感词如下:')
for item in sensitive_find:
print(item)
print('敏感词位置已用星号进行标注:\n' + newword)
Output result:
Please input or copy the promotional text containing sensitive words:
His technique is absolutely top-notch, he can be called the number one in the country, a national master!
The sensitive words are found as follows:
First: 1 time
National level: 1 time
First-rate: 1 time
Absolute: 1 time
The position of the sensitive word has been marked with an asterisk:
His technology is absolutely first-class, he can be called the first in the country, a national master!
Use anonymous function and max function to get the maximum number in the digital string
num = '2748123'
max_num = max(num, key=lambda x: int(x))
print(max_num)
output:
8
Use the string replacement method to remove the specified substring
with open('users.txt') as rfile:
str1 = rfile.readline()
str2 = str1.replace('\n', '')
print(str1 == str2)
输出结果:
False
利用列表推导式去除指定子字符串
word = '赵 钱 孙 李 周 吴 郑 王'
word = ''.join([i for i in word if i != ' '])
print(word)
Output result:
Zhao, Qian, Sun, Li, Zhou, Wu, Zheng, and Wang
Use string slicing to remove the substring at the specified position
str = 'I love 40982345Python! '
new_str = str[:2] + str[10:]
print(new_str)
output:
I love Python!
Use the Chinese character to pinyin module to arrange Chinese characters in pinyin order
Import Chinese characters to pinyin module
from xpinyin import Pinyin
names = ['张三', '李四', '王五', '赵六', '田七']
pin = Pinyin() # 创建汉字转拼音对象
temp = [] # 保存转换结果的空列表
for i in names:
# 获取汉字的拼音,跟汉字组合成元组放到临时列表中
temp.append((pin.get_pinyin(i), i))
print(temp) # 输出获取拼音后的列表
temp.sort() # 对列表进行排序
result = [] # 保存排序后的列表
for i in range(len(temp)):
result.append(temp[i][1]) # 取出汉字保存到新列表中
print(result)
Output result:
[('zhang-san', 'Zhang San'), ('li-si', 'Li Si'), ('wang-wu', 'Wang Wu'), ('zhao-liu', 'Zhao Liu'), ('tian-qi', 'Tian Qi')]
['Li Si', 'Tian Qi', 'Wang Wu', 'Zhang San', 'Zhao Liu']
The above content is quoted from Toutiao, the original author: FYK, see the link below.
https://www.toutiao.com/article/7174969369184223802/