Python 如何从字符串中提取第一个和最后一个单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41228115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract the first and final words from a string?
提问by Lior Dahan
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 print the first and final words of that string.
我的任务是从用户 ( text = raw_input()
)获取原始输入字符串,我需要打印该字符串的第一个和最后一个单词。
Can someone help me with that? I have been looking for an answer all day...
有人可以帮我吗?我一整天都在寻找答案......
回答by Moinuddin Quadri
You have to firstly convert the string to list
of words using str.split
and then you may access it like:
您必须首先使用将字符串转换list
为单词str.split
,然后您可以像这样访问它:
>>> 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:
从 Python 3.x 开始,您可以简单地执行以下操作:
>>> first, *middle, last = my_str.split()
回答by Anand Chitipothu
If you are using Python 3, you can do this:
如果您使用的是 Python 3,您可以这样做:
text = input()
first, *middle, last = text.split()
print(first, last)
All the words except the first and last will go into the variable middle
.
除了 first 和 last 之外的所有单词都将进入变量middle
。
回答by toom
Let's say x
is your input. Then you may do:
假设x
是您的输入。那么你可以这样做:
x.partition(' ')[0]
x.partition(' ')[-1]
回答by Mike
You would do:
你会这样做:
print text.split()[0], text.split()[-1]
回答by quapka
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']
回答by Cybernetic
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.']