Python相当于chartR

时间:2017-08-31 08:23:18

标签: python replace

chartr()(R)函数的生活非常简单:

txtdata = "my têxt is plaîn of accent"
chartr("îêéè", "ieee", txtdata)

返回"my text is plan of accent"

在Python中,re.sub()函数在第二个arg上只占用一个替换值:

re.sub("[éè]", "e", txtdata)

是否有与Chartr()相同的Python函数?

2 个答案:

答案 0 :(得分:4)

我相信str.translate更适合这样的任务,因为重音翻译。

out = "my têxt is plaîn of accent".translate(str.maketrans("îêéè", "ieee"))
print(out)
'my text is plain of accent'
100000 loops, best of 3: 3.05 µs per loop 

答案 1 :(得分:0)

def chartr(to_replace=None,to_replace_by=None,text=None):
      if len(to_replace) == len(to_replace_by):
            to_replace = list(to_replace)
            to_replace_by = list(to_replace_by)
            for i in range(0,len(to_replace)):
                  text = re.sub(to_replace[i], to_replace_by[i], text)
            return(text)
      else:
            return("length must be the same")
chartr("éeàâäî","eeaaai",body)