5 Best Ways to Find the Length of the Last Word in a String in Python

πŸ’‘ Problem Formulation: We often deal with processing text strings where we need to find the length of the last word. For instance, given the input string “Stay curious and keep learning”, we desire the output to be “8”, which corresponds to the length of the last word “learning”. This article explores multiple methods to achieve this in Python.

Method 1: Using str.split() and len()

One of the simplest methods to determine the length of the last word in a string is to use the split() method to create a list of words, and then apply the len() function to the last item on the list.

Here’s an example:

sentence = "Stay hungry, stay foolish"
words = sentence.split()
last_word_length = len(words[-1])
print(last_word_length)

Output:

7

This snippet splits the sentence into a list of words and computes the length of the last word by accessing it via words[-1]. This method is very straightforward and works well with properly spaced text.

Method 2: Using rsplit()

The rsplit() method is similar to split(), but it starts splitting from the end of the string. This can be more efficient if only the last word length is required and not the entire list of words.

Here’s an example:

sentence = "Never stop exploring"
last_word_length = len(sentence.rsplit(' ', 1)[1])
print(last_word_length)

Output:

9

By using rsplit() with 1 as a second argument, Python splits the sentence only once from the right side, giving us the last word directly. Then, len() is used to get its length.

Method 3: Using Regular Expression (re)

With the re module, we use regular expressions to capture the last word. This method is more flexible and can handle cases with multiple delimiter characters.

Here’s an example:

import re
sentence = "Innovation distinguishes between a leader and a follower."
match = re.search(r'\b(\w+)\b\s*$', sentence)
last_word_length = len(match.group(1)) if match else 0
print(last_word_length)

Output:

7

This code uses a regular expression to find a word boundary followed by one or more word characters (\w+), followed by a word boundary at the end of the string (\b\s*$). If a match is found, it retrieves the word and calculates its length.

Method 4: Using String Slicing

String slicing can be used to extract the last word without using any additional functions or methods, relying on Python’s built-in ability to manipulate strings.

Here’s an example:

sentence = "Design is not just what it looks like and feels like. Design is how it works."
last_space_index = sentence.rfind(' ') + 1
last_word = sentence[last_space_index:]
last_word_length = len(last_word)
print(last_word_length)

Output:

5

This snippet finds the index of the last space using rfind() and extracts the last word from the sentence using slicing. The length of this last word is then returned.

Bonus One-Liner Method 5: Using String Methods in a One-Liner

A concise way to find the length of the last word is to combine string methods into a one-liner. This method is for those who prefer compact code.

Here’s an example:

last_word_length = len("Empathy is a starting point for creating a community".rpartition(' ')[-1])
print(last_word_length)

Output:

9

The rpartition function splits the string at the last occurrence of the given argument and returns a tuple. The last element of this tuple is the word following the last space, the length of which is then computed.

Summary/Discussion

  • Method 1: Using str.split() and len(). Strengths: Intuitive and straightforward. Weaknesses: Not the most efficient for large strings when only the last word’s length is needed.
  • Method 2: Using rsplit(). Strengths: More efficient than method 1 when dealing with only the last word. Weaknesses: Assumes that words are delimited by spaces only.
  • Method 3: Using Regular Expression (re). Strengths: Very powerful, can handle complex string patterns. Weaknesses: Can be less readable and overkill for simple cases.
  • Method 4: Using String Slicing. Strengths: Does not rely on any library, very Pythonic. Weaknesses: Requires understanding of index manipulation.
  • Method 5: Bonus One-Liner. Strengths: Compact and elegant. Weaknesses: May sacrifice readability for brevity.