如何从字符串中提取第一个和最后一个单词? [英] How to extract the first and final words from a string?

查看:218
本文介绍了如何从字符串中提取第一个和最后一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学校需要做的事情有一个小问题...

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

我的任务是从用户(text = raw_input())获取原始输入字符串 并且我需要打印该字符串的开头和结尾单词.

My task is the get a raw input string from a user (text = raw_input()) and I need to print the first and final words of that string.

有人可以帮我吗?我整天都在寻找答案...

Can someone help me with that? I have been looking for an answer all day...

推荐答案

首先必须使用

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

在Python 3.x 中,您可以简单地执行以下操作:

From Python 3.x, you may simply do:

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

这篇关于如何从字符串中提取第一个和最后一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆