2
我试图拉弦的最后一个字,例如:从python中的字符串中提取最后一个字符?
x='hello, what is your name?'
x=x[:-1] #to remove question mark
lastword=findlastword(x)
print(lastword)
结果:“名字”
我试图拉弦的最后一个字,例如:从python中的字符串中提取最后一个字符?
x='hello, what is your name?'
x=x[:-1] #to remove question mark
lastword=findlastword(x)
print(lastword)
结果:“名字”
您可以去除标点符号和拆分文本(含空格str.split()
方法的默认参数),然后使用一个索引来获得最后一个字:
>>> import string
>>> x = 'hello, what is your name?'
>>>
>>> x.strip(string.punctuation).split()[-1]
'name'
有使用正则表达式的另一种方式,我不推荐这项任务:
>>> import re
>>> re.search(r'\b(\w+)\b\W$',x).group(1)
'name'