2

I am trying to pull the last word of a string, Example:

x='hello, what is your name?'
x=x[:-1] #to remove question mark 
lastword=findlastword(x)
print(lastword)

results : "name"

1 Answer 1

1

You can strip the text with punctuation and split (with whitespaces the default argument of str.split() method) then use a indexing to get the last word:

>>> import string
>>> x = 'hello, what is your name?'
>>> 
>>> x.strip(string.punctuation).split()[-1]
'name'

There is another way using regex which I don't recommend it for this task:

>>> import re
>>> re.search(r'\b(\w+)\b\W$',x).group(1)
'name'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.