python之string.maketrans和str.translate
2017-04-04 15:51
323 查看
转载地址:http://blog.csdn.net/skyin333/article/details/8661131
示例:
[python] viewplain copy
import string
s = 'abcd--dcba'
# 参数from和to的长度必须一致
table = string.maketrans('', '') # type(table) is 'str'
print(s.translate(table)) # 输出 abcd--dcba
table = string.maketrans('ab', '12')
print(s.translate(table)) # 输出 12cd--dc21
# 将先删除'ad',然后再转换
print(s.translate(table, 'ad')) # 输出 2c--c2
doc:
string.maketrans(from,to)Return a translation table suitable for passing to translate(),
that will map each character in from into the character at the same position in to;from and to must have the same length.
Note
Don’t use strings derived from lowercase and uppercase as
arguments; in some locales, these don’t have the same length. For case conversions, always usestr.lower() andstr.upper().
str.translate(table[,deletechars])
Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.
You can use the maketrans() helper
function in the string module
to create a translation table. For string objects, set the table argument to None for translations that only delete characters:
>>> 'read this short text'.translate(None, 'aeiou') 'rd ths shrt txt'
New in version 2.6: Support for a None table argument.
For Unicode objects, the translate() method
does not accept the optionaldeletechars argument. Instead, it returns a copy of thes where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings
or None. Unmapped characters are left untouched. Characters mapped to None are deleted. Note, a more flexible approach is to create a custom character mapping codec using the codecs module
(see encodings.cp1251 for an example).
相关文章推荐
- python之string.maketrans和str.translate
- Python——maketrans和translate方法,可以用来从string中替换和删除字符
- Python——maketrans和translate方法,可以用来从string中替换和删除字符
- Python——maketrans和translate方法,可以用来从string中替换和删除字符
- Python——maketrans和translate方法,可以用来从string中替换和删除字符
- python 中闭包理解,及函数string.maketrans(),string.translate()
- python中的maketrans和translate
- python 中 unicode原样转成str, unicode-escape与string_escape
- Python2.x和3.x下maketrans与translate函数使用上的不同
- Python——maketrans和translate方法
- python str.translate()函数用法
- Oracle select --字符函数:TRANSLATE(string,from_str,to_str)
- 轻松python文本专题-maketrans和translate
- 闭包在python中的应用,translate和maketrans方法详解
- string下的 maketrans和translate
- 轻松python文本专题-maketrans和translate
- python string.py 源码分析 三:maketrans
- python中用string.maketrans和translate巧妙替换字符串
- 闭包在python中的应用之translate和maketrans用法详解
- Python——maketrans和translate方法到底是什么玩意儿