使用translate from python 2 to python 3

2024-10-01 11:34:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个来自python2.7的遗留代码,其中包含:

f = lambda x:x.translate(None, "1234567890_")

此lambda函数用于生成如下字符串:

>> my_string = "hello_i_am_from_casablanca78"

看起来像这样:

>> print f(my_string)
>> "helloiamfromcasablanca"

python3这已经不起作用了,还有其他简单的方法吗?你知道吗

因为我在python3上试过了,得到了以下错误:

'str' does not support the buffer interface

如果我删除编码,我会得到:

TypeError: translate() takes exactly one argument (2 given)

非常感谢。你知道吗


Tags: lambda函数字符串代码fromnonehellostring
2条回答

那个羔羊看起来太晦涩了,无法挽救。你知道吗

更简单地说,您可以使用:

def f(s): 
    return ''.join(c for c in s if not c in '1234567890_'

这是使^{}在python3中工作的一种方法:首先使用^{}创建一个表:

tr_tbl = str.maketrans('','' , "1234567890_")
print('hello_i_am_from_casablanca78'.translate(tr_tbl))

相关问题 更多 >