python中字符串(string)的translate()和maketrans()方法


解释

  使用translate方法来对字符串中的具体字符进行替换,如使用12345来替换aeiou。而使用translate方法需要先使用maketrans方法来构建替换表
  注:python2的maketrans方法需要导入,而python3为内建。在python3中使用python2的语法来导入会报错ImportError: cannot import name ‘maketrans’

str.maketrans()

python文档的解释

Help on built-in function maketrans in str:

str.maketrans = maketrans(...)
Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.

str.translate()

python文档的解释

Help on method_descriptor in str:

str.translate = translate(self, table, /)
Replace each character in the string using the given translation table.

table
Translation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list. If this operation raises LookupError, the character is
left untouched. Characters mapped to None are deleted.

例子

将aeiou分别替换为12345


trantab = str.maketrans("aeiou", "12345")

print ("EXAMPLE:aeiou".translate(trantab))

输出为

EXAMPLE:12345

原创:https://www.panoramacn.com
源码网提供WordPress源码,帝国CMS源码discuz源码,微信小程序,小说源码,杰奇源码,thinkphp源码,ecshop模板源码,微擎模板源码,dede源码,织梦源码等。

专业搭建小说网站,小说程序,杰奇系列,微信小说系列,app系列小说

python中字符串(string)的translate()和maketrans()方法

免责声明,若由于商用引起版权纠纷,一切责任均由使用者承担。

您必须遵守我们的协议,如果您下载了该资源行为将被视为对《免责声明》全部内容的认可-> 联系客服 投诉资源
www.panoramacn.com资源全部来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。 敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:2640602276@qq.com
未经允许不得转载:书荒源码源码网每日更新网站源码模板! » python中字符串(string)的translate()和maketrans()方法
关注我们小说电影免费看
关注我们,获取更多的全网素材资源,有趣有料!
120000+人已关注
分享到:
赞(0) 打赏

评论抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

您的打赏就是我分享的动力!

支付宝扫一扫打赏

微信扫一扫打赏