Python 3 中 str.translate 的自定义表 [英] Custom table for str.translate in Python 3

查看:69
本文介绍了Python 3 中 str.translate 的自定义表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行此代码:

s.translate(str.maketrans({'as': 'dfg', '1234': 'qw'}))

我会得到:

ValueError: 转换表中的字符串键长度必须为 1

有没有办法使用 str.translate 一次替换多个字符?文档说我可以使用 codecs 来实现灵活的方法,但我不知道如何使用.

如果不是,那么可以做些什么呢?

解决方案

.str.translate 可以单独用于替换单个字符.替换字符串可以是任意长度,但必须是单个字符.

<小时>

当他们的文档提到 codecs 时,他们说你可以实现自定义编码,注册它然后使用它打开文件......这不是调用像 codecs 这样的东西的问题.maketrans,这是相当多的工作.我个人将 re.sub 与函数替换一起使用:

replacements = {'as': 'dfg', '1234': 'qw'}re.sub('({})'.format('|'.join(map(re.escape, replacements.keys()))), lambda m: replacements[m.group()], text)

这似乎可以满足您的需求:

<预><代码>>>>re.sub('({})'.format('|'.join(map(re.escape, replacements.keys()))), lambda m: replacements[m.group()], "test as other测试 1234")'测试 dfg 其他 testqw'

If I run this code:

s.translate(str.maketrans({'as': 'dfg', '1234': 'qw'}))

I will get:

ValueError: string keys in translate table must be of length 1

Is there a way to replace multiple characters at once using str.translate? Docs says I can use codecs for flexible approach, but I can't find out how.

If no, what can be done instead then?

解决方案

No. str.translate can be used solely to replace single characters. The replacement strings can be of any length, but the keys must be a single character.


When they documentation mentions codecs they are saying that you can implement a custom encoding, register it and then open the file using it... it's not a matter of calling something like codecs.maketrans, it's quite some work. I'd personally use re.sub with a function replacement:

replacements = {'as': 'dfg', '1234': 'qw'}
re.sub('({})'.format('|'.join(map(re.escape, replacements.keys()))), lambda m: replacements[m.group()], text)

Which seems to do what you want:

>>> re.sub('({})'.format('|'.join(map(re.escape, replacements.keys()))), lambda m: replacements[m.group()], "test as other test1234")
'test dfg other testqw'

这篇关于Python 3 中 str.translate 的自定义表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆