Search code examples
pythonstringstrip

Remove first word from string if length is 1


I want to remove the first character in a string, and the white space after it, only if the first word is one character.

Like this:

input = "A fish"
output = "fish"

Is there a way to do this without turning it into a list first?


Solution

  • You can do this with indexing:

    def remove_first(s):
        if len(s) < 2:
            return s
        # if string is letter then a space then trim the first 2 chars
        if s[0].isalpha() and s[1].isspace():
            return s[2:]
        return s
    
    remove_first("A fish") # "fish"
    remove_first("fish") # "fish"