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"
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'