Using .translate() on a string to strip digits [Python 3]

后端 未结 2 781
心在旅途
心在旅途 2020-12-07 03:59

Let\'s say I have the string \'2okjser823ab\'. How can I remove all the numbers from the string using .translate()?

I see that in Python 2.x you can do something li

相关标签:
2条回答
  • 2020-12-07 04:18

    You may use the strip function :

    strings="tycoon0123456789999"
    strings.strip("0123456789")
    
    0 讨论(0)
  • 2020-12-07 04:19

    It looks like it's a bit harder in Python 3; not sure why.

    Here's what you can do:

    >>> import string
    >>> translation = str.maketrans(string.ascii_letters, string.ascii_letters, string.digits)
    >>> "2okjser823ab".translate(translation)
    'okjserab'
    

    You may need to expand string.ascii_letters with whatever else you expect as input (string.ascii_letters + string.punctuation + string.whitespace, for example).

    Edit: I can't find it clearly in the documentation for str.maketrans, but if you use an empty string for the first two arguments, everything will be mapped 1 to 1, but the deletion part (the third argument) still happens:

    >>> translation = str.maketrans("", "", string.digits)
    >>> "2eeŷýéeokjser823 ab.;\t".translate(translation)
    'eeŷýéeokjser ab.;\t'
    
    0 讨论(0)
提交回复
热议问题