简体   繁体   中英

usage of translate from python 2 to python 3

I have a legacy code from python2.7 with in it:

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

this lambda function is used to make a string like this:

>> my_string = "hello_i_am_from_casablanca78"

to look like this:

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

In python3 this is no longer working, is there another simple way to do this?

Because I've tried on python3 and I get the following error:

'str' does not support the buffer interface

if I remove the encoding I get this:

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

Many thanks.

this is one way to get translate to work in python3: you create a table using mktrans first:

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

That lambda seems too obscure to salvage.

More simply you could just use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM