Python: reperire la lunghezza dell'ultima parola in una stringa

In questo articolo vedremo come ottenere la lunghezza dell'ultima parola in una stringa con Python.

Possiamo utilizzare la seguente funzione.


import re


def length_of_last_word(s):
    if not isinstance(s, str) or len(s) == 0:
        return 0
    limit = 10000
    length = len(s)
    if length > limit:
        return 0
    parts = s.strip().split(' ')
    if len(parts) == 0:
        return 0
    if len(parts) == 1:
        return len(parts[0].strip())
    values = list(filter(lambda v: not re.search(r'^\s+$', v), parts))
    if len(values) == 0:
        return 0
    if len(values) == 1:
        return len(values[0])
    last_word = values[-1:][0]
    return len(last_word)

Esempio d'uso:


def main():
    tests = ['Hello World', '   fly me   to   the moon  ',
             'luffy is still joyboy']
    for test in tests:
        print(test, length_of_last_word(test))


if __name__ == '__main__':
    main()

Torna su