Next / Previous / Contents / Shipman's homepage

11.11. BirdId.commafy(): Invert word order (static method)

This handy method rearranges an English name so that the last word comes first, followed by a comma, followed by the rest of the name.

abbr.py
# - - -   B i r d I d . c o m m a f y   - - -

#   @staticmethod
    def commafy ( eng ):
        """Transform 'Great Blue Heron' -> 'Heron, Great Blue'

          [ eng is a string ->
              if eng has no internal spaces or ends with " sp." ->
                return eng
              else ->
                return (last word of eng)+", "+(other words of eng) ]
        """
        #-- 1 --
        if  eng.endswith ( ' sp.' ):
            return eng

        #-- 2 --
        # [ wordList  :=  eng, broken at each region of whitespace ]
        wordList = eng.split()

        #-- 3 --
        # [ if len(wordList) < 2 ->
        #     return eng
        #   else ->
        #     return wordList[-1] + ", " + (wordList[:-1], joined
        #         by spaces ]
        if  len(wordList) < 2:
            return eng
        else:
            result = ( "%s, %s" %
                         (wordList[-1], " ".join(wordList[:-1])) )
            return result

    commafy = staticmethod(commafy)