Search code examples
pythonregexwhitespaceremoving-whitespace

Remove Space at end of String but keep new line symbol


How can I check if a Python string at any point has a single space before new line? And if it does, I have to remove that single space, but keep the new line symbol. Is this possible?


Solution

  • def remspace(my_str):
        if len(my_str) < 2: # returns ' ' unchanged
            return my_str
        if my_str[-1] == '\n':
            if my_str[-2] == ' ':
                return my_str[:-2] + '\n'
        if my_str[-1] == ' ':
            return my_str[:-1]
        return my_str
    

    Results:

    >>> remspace('a b c')
    'a b c'
    >>> remspace('a b c ')
    'a b c'
    >>> remspace('a b c\n')
    'a b c\n'
    >>> remspace('a b c \n')
    'a b c\n'
    >>> remspace('')
    ''
    >>> remspace('\n')
    '\n'
    >>> remspace(' \n')
    '\n'
    >>> remspace(' ')
    ' '
    >>> remspace('I')
    'I'