Search code examples
pythonstringwhile-loopslice

Is there a way to make this code cleaner without using the strip method?


This code will remove leading and trailing whitespace, newline, and tab. Is there a way to make it cleaner, without using the strip method?

def clean(message):
    while message[0] in '\n':
        message = message[1:]
    while message[0] in '\t':
        message = message[1:]
    while message[0] in ' ':
        message = message[1:]
    while message[-1] in '\t':
        message = message[:-1]
    while message[-1] in ' ':
        message = message[:-1]
    while message[-1] in '\n':
        message = message[:-1]
    while message[-1] in ' ':
        message = message[:-1]
    return message

Solution

  • You can use strip. By default strip removes all white-space characters e.g. '\n', '\t', ' ', from both beginning and end.

    def clean(message):
        return message.strip()
    

    Or you can use message.strip('\n\t ') if you want to be more explicit. You can add other characters to remove additional characters from both ends.

    Since this is builtin method, it will be a lot faster than the while loops.


    Not using strip at OP's request: Simply combining some while loops

    def clean(message):
        while message[0] in '\n\t ':
            message = message[1:]
        while message[-1] in '\n\t ':
            message = message[:-1]
        return message
    

    It's also better to use index, so you don't have to modify message in every loop. Faster this way too.

    def clean(message):
        start, end = 0, -1
        while message[start] in '\n\t ':
            start += 1
        while message[end] in '\n\t ':
            end -= 1
        return message[start:end]