查找通讯录
-- coding: utf-8 --with open(‘contacts.txt’) as fp: lines = fp.readlines()found = Falsename = input(“input the name:”)for eachline in lines: c_name, phone_num = eachline.split(’,’) if name == c_name: print(eachline) found = True breakif not found: print(“not found!”)
判断文件名
def isident(s): if not(s[0].isalpha() or s[0] == ‘’): return False for ch in s: if not(ch.isalnum() or ch == '’): return False return Truewith open(‘name.txt’, ‘w+’) as fp: s = input("Input the string: ") while s != ‘END’: if isident(s): fp.write(s + ‘\n’) s = input(“Input the string:”) fp.seek(0) print(fp.read())
读取字幕
with open(‘subtitles.srt’, ‘r’) as fp1: with open(‘subtitles.txt’, ‘w’) as fp2: for line in fp1.readlines(): if line[0].isdigit() == 0 and len(line) != 1: fp2.write(line)
Qq号查找
-- coding: utf-8 --def find_QQ(dict_users, name): if dict_users.get(name): return dict_users[name] else: return None def find_luckyguys(dict_users): lst = [] for key, value in dict_users.items(): if value < 100000: lst.append(key) return lstif name == “main”: dict_users = {‘小明’:88888,‘阿花’:5555555,‘大壮’:11111,‘大毛’:1234321,‘小毛’:1212121} count = 0 name = input("Please enter the name: ") while True: count += 1 QQ = find_QQ(dict_users, name) if QQ: print(‘The QQ number of {} is: {}’.format(name, QQ)) break elif count < 3: name = input('Enter the name again: ') else: print(‘Bye!’) break lst = find_luckyguys(dict_users) print('The lucky guys are: ', lst)
两数互质
-- coding: utf-8 --""“Created on Thu Nov 12 14:57:31 2020@author: Administrator”"“from random import randinta=randint(0,100)b=randint(0,100)if a%b0 or b%a0: print(”{} and {} are not coprime.".format(a,b))else: print("{} and {} are coprime.".format(a,b))
判断字符串合法
def CheckId(s): alphas = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_’ nums = ‘0123456789’ if len(s) > 1: firstChar = s[0] if firstChar not in alphas: print(‘Error. First char must be alphas or _.’) else: otherChar = s[1:] alphasnums = alphas + nums for c in otherChar: if c not in alphasnums: print(‘Error. Other chars must be alphas number or _ .’) break else: print(‘Valid identifier.’) if name == “main”: CheckId(input('Enter a string please: '))
单词统计