How to extract the first and final words from a string?

耗尽温柔 提交于 2019-12-01 02:27:57

You have to firstly convert the string to list of words using str.split and then you may access it like:

>>> my_str = "Hello SO user, How are you"
>>> word_list = my_str.split()  # list of words

# first word  v              v last word
>>> word_list[0], word_list[-1]
('Hello', 'you')

From Python 3.x, you may simply do:

>>> first, *middle, last = my_str.split()

If you are using Python 3, you can do this:

text = input()
first, *middle, last = text.split()
print(first, last)

All the words except the first and last will go into the variable middle.

toom

Let's say x is your input. Then you may do:

 x.partition(' ')[0]
 x.partition(' ')[-1]

You would do:

print text.split()[0], text.split()[-1]

Some might say, there is never too many answer's using regular expressions (in this case, this looks like the worst solutions..):

>>> import re
>>> string = "Hello SO user, How are you"
>>> matches = re.findall(r'^\w+|\w+$', string)
>>> print(matches)
['Hello', 'you']

Simply pass your string into the following function:

def first_and_final(str):
    res = str.split(' ')
    fir = res[0]
    fin = res[len(res)-1]
    return([fir, fin])

Usage:

first_and_final('This is a sentence with a first and final word.')

Result:

['This', 'word.']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!