#将字符“abcdef123”一 一对应地转换成"uvwxyz@#$"
table =' '.maketrans("abcdef123","uvwxyz@#$")
s ="Python is a greate programing language.i like it!"
s.translate(table)
'Python is u gryuty progruming lunguugy.i liky it!'
import string
import random
x = string.digits+string.ascii_letters+string.punctuation #数字+字母++分隔符
code =" ".join([random.choice(x)for i inrange(8)])#随机挑选x中的某个字符,挑选8次生成列表,列表中的字符再被空格join为字符串print(code)
) p 7 : x O w Q
发红包算法
import random
defred_packet(total,num):# total 红包总额# num红包数量
each =[]#已发红包金额
already =0for i inrange(1,num):#range(a,b)-->[a,b)
t = random.randint(1,(total-already)-(num -i))#至少为剩下的每个人留一块钱
each.append(t)#将每个人拿的红包额度记录到each列表
already += t
#剩余所有钱发给最后1个人
each.append(total-already)
random.shuffle(each)return each
for i inrange(5):
each = red_packet(50,6)print(each)
import io
s ="Hello,world"
sio = io.StringIO(s)
sio.getvalue()
'Hello,world'
sio.seek(7)
7
sio.write("there!")
6
sio.getvalue()
'Hello,wthere!'
字符串加密解密
defcrypt(source, key):from itertools import cycle
result =''
temp=cycle(key)#将密码字key变成可迭代对象for ch in source:
result = result +chr(ord(ch)^ord(next(temp)))#密码的ASCII码与加密码字进行异或操作得到结果return result
source ="No romatic in China"
key ="i love you so"print("before encrypted:",source)
encrypted = crypt(source, key)print("after encrypted:",encrypted)
decrypted = crypt(encrypted,key)print("after decrypted:",decrypted)
before encrypted: No romatic in China
�Ic
after decrypted: No romatic in China