用Python实现的rot13编解码


#一目了然版
def rot13(s):
    result = ""
    for v in s:
        c = ord(v)
        if c >= ord('a') and c <= ord('z'):
            if c > ord('m'):
                c -= 13
            else:
                c += 13
        elif c >= ord('A') and c <= ord('Z'):
            if c > ord('M'):
                c -= 13
            else:
                c += 13
        result += chr(c)
    return result
#小写字母(不完全版)
def rot13(s):
    chars = "abcdefghijklmnopqrstuvwxyz"
    trans = chars[13:] + chars[:13]
    rot_char = lambda c: trans[chars.find(c)] if chars.find(c)>-1 else c
    return ''.join( rot_char(c) for c in s )
import string
def make_rot_n(n):
	lc = string.lowercase
	trans = string.maketrans(lc, lc[n:] + lc[:n])
	return lambda s: string.translate(s, trans)
rot13 = make_rot_n(13)

print rot13('gandalf')
d = {}
for c in (65, 97):
    for i in range(26):
        d[chr(i+c)] = chr((i+13) % 26 + c)

print "".join([d.get(c, c) for c in s])
#大小写字母
def rot13(s):
	rot = lambda x:chr(ord(x)+13) if chr(ord(x.lower())+13).isalpha()==True else chr(ord(x)-13)
	s = [rot(i) for i in filter(lambda x:x!=',', map(str,s))]
	return ''.join(s)
def rot13(s):
    chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
    trans = chars[26:] + chars[:26]
    rot_char = lambda c: trans[chars.find(c)] if chars.find(c) > -1 else c
    return ''.join(rot_char(c) for c in s)
#zip/map/join
def rot13(string):
    CLEAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    ROT13 = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
    TABLE = {x: y for x, y in zip(CLEAR, ROT13)}

    return ''.join(map(lambda x: TABLE.get(x, x), string))
#yield
def rot13(clear):
    CLEAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    ROT13 = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
    TABLE = {x: y for x, y in zip(CLEAR, ROT13)}

    for c in clear:
        yield TABLE.get(c, c)
#自定义Offset
def rot13(s, OffSet=13):
	def encodeCh(ch):
		f = lambda x: chr((ord(ch)-x+OffSet) % 26 + x)
		return f(97) if ch.islower() else (f(65) if ch.isupper() else ch)
	return ''.join(encodeCh(c) for c in s)

s = 'Hello!'
print rot13(s)			# Uryyb!
print rot13(rot13(s))	# Hello!
print rot13(s, 26)		# Hello!
参考链接:
,

《“用Python实现的rot13编解码”》 有 1 条评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注