python 的 maketrans & translate 文本字符串替换

您所在的位置:网站首页 pythontranslate函数 python 的 maketrans & translate 文本字符串替换

python 的 maketrans & translate 文本字符串替换

2023-09-01 11:04| 来源: 网络整理| 查看: 265

maketrans(): 描述

maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

两个字符串的长度必须相同,为一一对应的关系。

注:Python3.4 已经没有 string.maketrans() 了,取而代之的是内建函数: bytearray.maketrans()、bytes.maketrans()、str.maketrans()

语法

str.maketrans ( intab , outtab )

参数 intab – 字符串中要替代的字符组成的字符串outtab – 相应的映射字符的字符串 返回值

返回字符串转换后生成的新字符串

示例 #!/usr/bin/python3 intab = "abcde" outtab = "./*?1" trantab = str.maketrans(intab, outtab) str = "Wow a boy Nice" print (str.translate(trantab)) # 结果: Wow . /oy Ni*1 translate(): 描述

translate() 方法根据参数table给出的表(包含 256 个字符)转换字符串的字符,要过滤掉的字符放到 deletechars 参数中。

语法

str.translate(table) bytes.translate(table[, delete]) bytearray.translate(table[, delete])

参数 table – 翻译表,翻译表是通过 maketrans() 方法转换而来。deletechars – 字符串中要过滤的字符列表。 返回值

返回翻译后的字符串,若给出了 delete 参数,则将原来的bytes中的属于delete的字符删除,剩下的字符要按照table中给出的映射来进行映射 。

示例 #!/usr/bin/python3 intab = "abcde" outtab = "./*?1" trantab = str.maketrans(intab, outtab) str = "Wow a boy Nice" print (str.translate(trantab)) # 结果: Wow . /oy Ni*1

过滤的字符 o :

#!/usr/bin/python # 制作翻译表 bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ') # 转换为大写,并删除字母o print(b'runoob'.translate(bytes_tabtrans, b'o')) # 结果 b'RUNB' import string text = ("g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc" "dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcv" "r gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnj" "w ml rfc spj.") table1 = string.ascii_lowercase # abcd...xyz table2 = table1[2:]+table1[:2] # cdef...zab trans = table1.maketrans(table1, table2) result = text.translate(trans) print(result) # 结果: # i hope you didnt translate it by hand. thats what computers arefor. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url.


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3