Search code examples
pythonstringstrip

Is there an elegant way to strip all alphabetic characters from the end of a string?


This works:

stripped_str = whatever_str.rstrip("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

but just seems very inelegant to me. Any cleaner way of doing it?


Solution

  • Perhaps you are looking for string.ascii_letters:

    from string import ascii_letters
    stripped_str = whatever_str.rstrip(ascii_letters)
    

    It allows you to do the same as your current code, but without typing the entire alphabet.

    Below is a demonstration:

    >>> from string import ascii_letters
    >>> ascii_letters
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    >>>
    >>> '123abdjihdkffyifbgh'.rstrip(ascii_letters)
    '123'
    >>>