In this article, we will learn how to remove the last word from the string in python. There are various ways to remove the last word from the string in python.
Here are various examples to remove the last word from the string in python.
In this example, we used the rsplit()
method and this method splits a string into a list, starting from the right.
Here is the source code of the program to remove the last word from the string using the rsplit()
function in javascript.
# How to Remove the Last word from the String using rsplit() in Python
str = 'Python: I want to remove the last word.'
print('Original String: ',str)
newStr = str.rsplit(' ', 1)[0]
print('\nFinal String: ',newStr)
Original String: Python: I want to remove the last word.
Final String: Python: I want to remove the last
In this example, we used the split()
and join()
method and this method returns a list of strings after breaking the given string by the specified separator.
Here is the source code of the program to remove the last word from the string using the split()
and join()
method in javascript.
# How to Remove the Last word from the String using join() and split() in Python
str = 'Python: I want to remove the last word.'
print('Original String: ',str)
' '.join(str.split(' ')[:-1])
print('\nFinal String: ',newStr)
Original String: Python: I want to remove the last word.
Final String: Python: I want to remove the last
In the example, we used the rfind()
method and this method returns the last index where the substring str is found, or -1 if no such index exists, optionally restricting the search to string[beg:end]
.
Here is the source code of the program to remove the last word from the string using the rfind()
method in javascript.
# How to Remove the Last word from the String using rfind() method in Python
str = 'Python: I want to remove the last word.'
print('Original String: ',str)
str[:str.rfind(' ')]
print('\nFinal String: ',newStr)
Original String: Python: I want to remove the last word.
Final String: Python: I want to remove the last
In the example, we used join()
and split()
methods using another approach.
Here is the source code of the program to remove the last word from the string - another approach using the join()
and split()
method in javascript.
# How to Remove the Last Word from the String using split() and join() method in Python
string = 'Python: I want to remove the last word.'
print('Original String: ',string)
#split string
spl_string = string.split()
#remove the last item in list
rm = spl_string[:-1]
#convert list to string
newStr = ' '.join([str(elem) for elem in rm])
#print string
print('\nFinal String: ',newStr)
Original String: Python: I want to remove the last word.
Final String: Python: I want to remove the last
I hope this article will help you to understand how to remove the last word from the string in Python.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments