Python last word in line

Given a string, the task is to write a Python program to print the last word in that string.

Examples:

Input: sky is blue in color

Output: color

Explanation: color is last word in the sentence.

Input: Learn algorithms at geeksforgeeks

Output: geeksforgeeks

Explanation: geeksforgeeks is last word in the sentence.

Approach #1: Using For loop + String Concatenation

  • Scan the sentence
  • Take an empty string, newstring.
  • Traverse the string in reverse order and add character to newstring using string concatenation.
  • Break the loop till we get first space character.
  • Reverse newstring and return it (it is the last word in the sentence).

Below is the implementation of the above approach:

Python3

def lastWord(string):

    newstring = ""

    length = len(string)

    for i in range(length-1, 0, -1):

        if(string[i] == " "):

            return newstring[::-1]

        else:

            newstring = newstring + string[i]

string = "Learn algorithms at geeksforgeeks"

print(lastWord(string))

Output:

geeksforgeeks

Approach #2: Using split() method

  • As all the words in a sentence are separated by spaces.
  • We have to split the sentence by spaces using split().
  • We split all the words by spaces and store them in a list.
  • The last element in the list is the answer

Below is the implementation of the above approach:

Python3

def lastWord(string):

    lis = list(string.split(" "))

    length = len(lis)

    return lis[length-1]

string = "Learn algorithms at geeksforgeeks"

print(lastWord(string))

Output:

geeksforgeeks

The time and space complexity for all the methods are the same:

Time Complexity: O(n)

Auxiliary Space: O(n)

Approach #3: Using rfind() method

In this approach, we use the rfind() method to find the index of the last space in the string.
The part of the string from the last space to the end of the string is the last word.
Below is the implementation of the above approach:

Python3

def lastWord(string):

  index = string.rfind(" ")

  return string[index+1:]

string = "Learn algorithms at geeksforgeeks"

print(lastWord(string))

Time Complexity: O(n)

Auxiliary Space: O(1)

Approach #4: Using reversed() function:

Algorithm:

  1. Reverse the given string.
  2. Find the index of the first space in the reversed string.
  3. Return the last word in the original string by taking a slice from the original string starting from the end of the
  4. reversed string to the position of the first space in the reversed string.

Python3

def lastWord(string):

    reversed_string = string[::-1]

    index = reversed_string.find(" ")

    return string[-index-1:]

string = "Learn algorithms at geeksforgeeks"

print(lastWord(string)) 

Time Complexity:
The time complexity of the find() function used in the implementation is O(n), where n is the length of the string. The slicing operation in Python also takes O(n) time complexity. Therefore, the overall time complexity of this algorithm is O(n).

Space Complexity:
The space complexity of this algorithm is O(n), where n is the length of the string. This is because we are creating a new string object by reversing the original string. However, the space complexity can be further optimized by iterating over the string from the end to find the last word instead of reversing the entire string

What’s the best way to slice the last word from a block of text?

I can think of

  1. Split it to a list (by spaces) and removing the last item, then reconcatenating the list.
  2. Use a regular expression to replace the last word.

I’m currently taking approach #1, but I don’t know how to concatenate the list…

content = content[position-1:position+249] # Content
words = string.split(content, ' ')
words = words[len[words] -1] # Cut of the last word

Any code examples are much appreciated.

pigrammer's user avatar

pigrammer

2,3201 gold badge9 silver badges24 bronze badges

asked Jun 7, 2011 at 14:26

qwerty's user avatar

Actually you don’t need to split all words. You can split your text by last space symbol into two parts using rsplit.

Example:

>>> text = 'Python: Cut off the last word of a sentence?'
>>> text.rsplit(' ', 1)[0]
'Python: Cut off the last word of a'

rsplit is a shorthand for «reverse split», and unlike regular split works from the end of a string. The second parameter is a maximum number of splits to make — e.g. value of 1 will give you two-element list as a result (since there was a single split made, which resulted in two pieces of the input string).

Jyri Keir's user avatar

answered Jun 7, 2011 at 14:32

Roman Bodnarchuk's user avatar

Roman BodnarchukRoman Bodnarchuk

29.2k12 gold badges58 silver badges75 bronze badges

3

You should definitely split and then remove the last word because a regex will have both more complications and unnecessary overhead. You can use the more Pythonic code (assuming content is a string):

' '.join(content.split(' ')[:-1])

This splits content into words, takes all but the last word, and rejoins the words with spaces.

answered Jun 7, 2011 at 14:32

murgatroid99's user avatar

murgatroid99murgatroid99

18.5k10 gold badges60 silver badges95 bronze badges

If you like compactness:

' '.join(content.split(' ')[:-1]) + ' ...'

answered Jun 7, 2011 at 14:35

Giacomo d'Antonio's user avatar

If you want to keep your current method, use ' '.join(words) to concatenate the list.

You also might want to replace words = words[len[words -1] with words = words[:-1] to make use of list slicing.

answered Jun 7, 2011 at 14:31

NickAldwin's user avatar

NickAldwinNickAldwin

11.5k12 gold badges50 silver badges67 bronze badges

OR

import re

print ' '.join(re.findall(r'bw+b', text)[:-1])

answered Jun 7, 2011 at 14:36

Artsiom Rudzenka's user avatar

Artsiom RudzenkaArtsiom Rudzenka

27.6k4 gold badges33 silver badges51 bronze badges

1

Get last index of space and splice the string

>>> text = 'Python: Cut of the last word of a sentence?'
>>> text[:text.rfind(' ')]
'Python: Cut of the last word of a'

answered Nov 15, 2017 at 10:02

Vikram Singh Chandel's user avatar

1

' '.join(words) will put the list back together.

answered Jun 7, 2011 at 14:28

Wooble's user avatar

WoobleWooble

87k12 gold badges107 silver badges131 bronze badges

        
def replace_ending(sentence, old, new):
    S1 = sentence
    O1 = old
    N1 = new
    # Check if the old string is at the end of the sentence 
    if O1 in S1:
        # Using i as the slicing index, combine the part
        # of the sentence up to the matched string at the 
        # end with the new string
        i = S1.rsplit(' ',1)[0] + str(" ") + N1     
        new_sentence = i
        return new_sentence

    # Return the original sentence if there is no match 
    return sentence
    
print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"

answered Dec 19, 2020 at 1:54

entryLVL-py3Guy's user avatar

1

Enother variant is to use an argument «args

For example:

def truncate_sentences(length, *sentences):
  for sentence in sentences:
    print(sentence[:length])

#call function

truncate_sentences(8, "What's going on here", "Looks like we've been cut off")

Would output:

"What's g"
"Looks li"

Let’s break this down:

  1. We have two parameters that our function truncate_sentences() defines. The first is a length parameter that will specify how many characters we want to keep. The second is a parameter called sentences that is paired with the unpacking operator, signifying it will take a variable number of arguments.
  2. On each iteration of the function, we are looping through the tuple created by the sentences argument (because it is paired with the unpacking operator) and perform a slice on the sentence based on the provided length argument. This forces every value in the sentences tuple to be cut down in length.

answered Aug 31, 2021 at 14:16

Pobaranchuk's user avatar

PobaranchukPobaranchuk

8198 silver badges13 bronze badges

Try Below,

def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence 
if sentence.endswith(old):
    # Using i as the slicing index, combine the part
    # of the sentence up to the matched string at the 
    # end with the new string
    i = sentence.rsplit(' ',1)[0] + str(" ")
    new_sentence = i + new
    return new_sentence

# Return the original sentence if there is no match 
return sentence

answered Feb 23, 2022 at 8:46

johnmist's user avatar

In this tutorial, I’ll discuss how you can get the last word from a given string in Python. It’s very easy to get the last word from a given string in Python. To get the last word from a string, we have to convert the string into a list at the first. After converting the string into a list, simply we can use the slicing operator to get the last word of the string and then we can print it. For converting a string into a list we can simply use the split() method.

Syntax:

your_string.split(Separator, Maxsplit)

Separator: This is optional. This is used to specify where we want to split the string. By default, it takes whitespace as a separator.

Maxsplit : This is also optional. This is used to specify how many splits we want to do in the given string. By default, it takes the value as -1, which means all the occurrences or no limit on the number of splits.

Now, let me give an example to understand the concept

#taking input from the user
string = input("Enter your string: ")

#splitting the string
words = string.split()

#slicing the list (negative index means index from the end)
#-1 means the last element of the list
print(words[-1])

Run this code online

Output :

Enter your string: Welcome to Codespeedy
Codespeedy

In this above code, I gave the input as ‘Welcome to Codespeedy’ and it gave me output as ‘Codespeedy’ that is the last word of the string.

So I hope now you’re familiar with the concept of how you can get the last word from a string.

Also read:

  • Python string rjust() and ljust() methods

Python предлагает много способов получить последний символ строки. Но чтобы в них разобраться, сперва нужно понять, как работает индексирование в Python. Чтобы указать, какой фрагмент строки вы хотите получить, можно использовать квадратные скобки, а в них поместить индекс нужного символа.

Например, в строке “stand firm in the faith” всего 23 символа.

testString = "stand firm in the faith"
print("The length of testString is: %d" % len(testString))

# Вывод:
# The length of testString is: 23

При этом последняя буква “h” имеет индекс 22. Почему 22, а не 23? Потому что в Python индексация начинается с 0. Т.е. первый символ в строке имеет индекс 0, второй – 1 и так далее.

Еще Python имеет замечательную особенность: индексация может идти и в обратном порядке! Просто используйте отрицательные числа, начиная с -1. Под индексом -1 будет последний символ строки, под индексом -2 – предпоследний и т.д.

Схема индексации на примере строки stand firm in the faith

Получаем последний символ строки

Чтобы получить последний символ строки, можно просто обратиться к нему по индексу. Но такое жесткое прописывание индекса связано с определенными проблемами. Для начала вы должны знать сам индекс, а для этого – длину строки. Далее мы опишем несколько лучших методов.

testString = "stand firm in the faith"
lastChar = testString[22]
print("The last character of testString is: %s" % lastChar)

# Вывод:
# The last character of testString is: h

Применение функции len()

Более детерминированный способ получения последнего индекса в строке – это использование функции len() для получения длины строки. В данном случае функция len() вернет 23. Чтобы получить индекс последнего символа, нужно вычесть единицу из длины строки.

testString = "stand firm in the faith"
lastChar = testString[len(testString) - 1]
print("The last character of testString is: %s" % lastChar)

# Вывод:
# The last character of testString is: h

Отрицательный индекс

Вероятно, самый простой способ получить последний символ строки в Python – это использовать отрицательные индексы. Использование отрицательных чисел для индексации в Python позволяет начать отсчет с конца строки. Таким образом, если в строке “stand firm in the faith” вам нужен только последний символ строки, можно обратиться к нему по индексу -1.

testString = "stand firm in the faith"
lastChar = testString[-1]
print("The last character of testString is: %s" % lastChar)

# Вывод:
# The last character of testString is: h

Осторожность при работе с пустой строкой

Все вышеперечисленные методы могут вызвать исключение, если мы не включим в программу проверку ошибок. В следующем примере мы создадим новую строку, в которой не будет ни одного символа. Если мы попытаемся обратиться по индексу к несуществующему символу, Python выбросит исключение.

sampleString = ""
lastChar = sampleString[-1]

Результат:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

Простой способ исправить этот пример – проверить, что наша строка имеет ненулевую длину (т.е. содержит какие-то символы).

testString = ""
if len(testString) > 0:
    lastChar = testString[len(testString) - 1]
    print("The last character of testString is: %s" % lastChar)
else:
    print("The string was empty")

# Вывод:
# The string was empty

Прежде чем пытаться извлечь первый, последний или любой другой символ строки, стоит убедиться, что такой индекс в строке есть, иначе получите исключение.

Получаем последние n символов строки

Вы также можете захватить не один последний символ, а несколько. Для этого мы будем использовать то, что в Python называется оператором среза.

При помощи среза можно задать диапазон символов. Для этого указываются индексы начала и конца диапазона символов (их разделяет двоеточие). Важно обратить внимание, что символ под начальным индексом войдет в срез, а под конечным – нет. Если при использовании среза вы получаете слишком много или слишком мало символов, то это, скорее всего, связано с непониманием того, как он используется.

testString = "stand firm in the faith"
extractedString = testString[6:10]
print("Extracted string: %s" % extractedString)

# Вывод:
# Extracted string: firm

Примечание редакции: о срезах можно почитать в статье “Срез массива в Python”. Срезы строк работают аналогично.

Как получить последние символы строки с помощью среза

Чтобы получить последние n символов, просто выберите начальный и конечный индекс для среза. Например, если мы хотим получить последнее слово нашей тестовой строки “stand firm in the faith”, мы используем начальный индекс 18. Конечный индекс можно не указывать. В таком случае по умолчанию срез будет до конца строки.

testString = "stand firm in the faith"
lastChars = testString[18:]
print("The last five character of testString is: %s" % lastChars)

# Вывод:
# The last five character of testString is: faith

Можно пойти другим путем и применить функцию len(). Для определения начального индекса среза из длины строки нужно будет вычесть 6. Мы вычитаем единицу, потому что индексация начинается с нуля, и еще 5 – потому что в последнем слове 5 символов.

testString = "stand firm in the faith"
lastChars = testString[len(testString)-6:]
print("The last five character of testString is: %s" % lastChars)

# Вывод:
# The last five character of testString is:  faith

Использование срезов с отрицательной индексацией

Этот вариант немного странный, но это может быть именно то, что вы ищете. Вы можете использовать отрицательную индексацию, чтобы указать начальный индекс, а затем не указывать конечный индекс, чтобы захватить остальную часть строки.

testString = "stand firm in the faith"
lastChars = testString[-5:]
print("The last five character of testString is: %s" % lastChars)

# Вывод:
# The last five character of testString is: faith

Как получить последнее слово в строке

Если вы имеете дело с предложениями и пытаетесь получить последнее слово в строке, лучше всего проделать некоторые манипуляции со строками.

Разделите исходную строку на массив новых строк с помощью функции split(). Первый аргумент функции split() указывает конкретный символ, по которому нужно разделить данную строку. Это может быть любой из символов Юникода, даже специальные символы. В нашем случае мы хотим разделить строку по пробелам. После разделения нам останется только выбрать одну из перечисленных выше техник для захвата последнего слова. Для примера используем отрицательный индекс.

testString = "stand firm in the faith"
words = testString.split(" ")
print("The last word of testString is: %s" % words[-1])

# Вывод:
# The last word of testString is: faith

Примечание редакции: о применении функции split() можно почитать в статье “Разделение строки в Python”.

Осторожно при работе с пустой строкой

Это менее рискованно, чем обращение к последнему элементу строки по индексу, поскольку функция split(), вызванная для пустой строки, вернет массив с содержимым [”], и исключение не будет выброшено. Тем не менее, хорошей практикой является добавление обработки ошибок, чтобы в дальнейшем в программе не возникало неожиданного поведения.

sampleString = ""
testString = ""
words = testString.split(' ')
print(words) 
print("The last word of testString is: %s" % words[-1])

# Вывод:
# ['']
# The last word of testString is: 

Ошибки нет, но это, вероятно, не тот результат, которого ожидает наш код. Исправление аналогично предыдущему примеру проверки ошибок:

testString = ""
if testString.count(" ") > 0:
    words = testString.split(' ')
    print("The last word of testString is: %s" % words[-1])
else:
    print("There was not multiple words in the string")

# Вывод:
# There was not multiple words in the string

В общем, независимо от того, сколько символов строки вы извлекаете, важно убедиться, что в строке их не меньше запрошенного числа.

Удаление пробельных символов из строки

Возможно, вы хотите получить последний символ строки, чтобы узнать, является он печатным или пробельным. Вместо того чтобы выписывать эту оценку, можно использовать один из встроенных строковых методов. В этом примере мы покажем, как использовать метод strip().

testString = "this string has white space on the end  "
print("[%s]" % testString)

# Вывод:
# [this string has white space on the end  ]
testString = "this string has white space on the end  "
testString = testString.strip()
print("[%s]" % testString)

# Вывод:
# [this string has white space on the end]

Как видите, метод strip() удалил пробелы из конца строки. Поэтому, если вы пытались получить последний символ, чтобы проверить, нужно ли удалять пробелы, метод strip() – гораздо более простой способ достижения той же цели.

Перевод статьи «Python: How to get the last character in a string».

In the previous article, we have discussed Python Program to Subtract two Complex Numbers

Given a string that contains the words the task is to print the last word in the given string in Python.

Examples:

Example1:

Input:

Given string =hello this is BTechgeeks

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Example2:

Input:

Given string =good morning this is btechgeeks

Output:

The last word in the given string { good morning this is btechgeeks } is: btechgeeks

Below are the ways to get the last word from the given string in Python.

  • Using split() Method (Static Input)
  • Using split() Method (User Input)

Method #1: Using split() Method (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'hello this is BTechgeeks'
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Method #2: Using split() Method (User Input)

Approach:

  • Give the string as user input using the input() function and store it in the variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in the variable.
gvnstrng = input('Enter some random string = ')
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

Enter some random string = good morning this is btechgeeks
The last word in the given string { good morning this is btechgeeks } is: btechgeeks

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

  • Python Program to Remove the First Occurrence of Character in a String
  • Program to Print Even Length Words in a String
  • Python Program to Print Nth word in a given String
  • Python Program to Remove all Consonants from a String

Понравилась статья? Поделить с друзьями:
  • Python and excel windows
  • Python if word not in list
  • Python and excel programming
  • Python if word in array
  • Python and excel pdf