Pythonic Way of replacing Multiple Characters

后端 未结 2 509
我寻月下人不归
我寻月下人不归 2021-01-15 22:22

I\'ve created a onetime function

a = lambda x: x.replace(\'\\n\', \'\')
b = lambda y: y.replace(\'\\t\', \'\').strip()
c = lambda x: b(a(x))
<
2条回答
  •  暖寄归人
    2021-01-15 22:51

    The improvements are pretty straightforward:

    Drop lambdas. str.replace() method is a function, and in the first line of your snippet you define a function that calls to another function and nothing else. Why do you need the wrapping lambda? The same concerns the second line.

    Use return values. Actually, in docs we see:

    Return a copy of the string with all occurrences of substring old replaced by new.

    So you can do a first replace(), then do a second one on the obtained result.

    To sum up, you'll have:

    c = x.replace('\n', '').replace('\t', '').strip()
    

    Note: if you have many characters to remove, you'd better use str.translate() but for two of them str.replace() is far more readable.

    Cheers!

提交回复
热议问题