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

前端 未结 6 1396
鱼传尺愫
鱼传尺愫 2020-12-31 00:49

I have a small problem with something I need to do in school...

My task is the get a raw input string from a user (text = raw_input()) and I need to pri

6条回答
  •  长发绾君心
    2020-12-31 01:27

    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.']
    

提交回复
热议问题