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

前端 未结 6 1401
鱼传尺愫
鱼传尺愫 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条回答
  •  Happy的楠姐
    2020-12-31 01:07

    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()
    

提交回复
热议问题