[英]Replacing a list of utf8 characters in Python
I have a list of Farsi characters (utf8) like this: 我有这样的波斯语字符(utf8)列表:
my_list = ['ﯾ', 'ﻲ', 'ﻴ']
And I would like to replace every occurrence of characters in this list in a text with another character like 'a'. 我想用另一个字符(例如“ a”)替换此列表中所有出现的字符。 Right now my code is like this:
现在我的代码是这样的:
text = text.replace('ﻴ', 'a')
text = text.replace('ﻲ', 'a')
text = text.replace('ﯾ', 'a')
Is there any way to do this in one shot, for example using Regex and lists in Python 3? 有什么方法可以一口气做到这一点,例如使用Regex和Python 3中的列表?
3>> 'ﻴ ﻲ ﯾ'.translate({0xfbfe: 'a', 0xfef2: 'a', 0xfef4: 'a'})
'a a a'
You could use a for loop instead: 您可以改用for循环:
for char in my_list:
text = text.replace(char,'a')
This way your list could be an arbitrary length but the size of your code wont change. 这样,您的列表可以是任意长度,但是代码的大小不会改变。 Plus you aren't repeating code.
另外,您无需重复代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.