Reputation: 762
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.
Can someone help me with that? I have been looking for an answer all day...
Upvotes: 27
Views: 115820
Reputation: 11357
Yet another possible implementation, which does not use split()
text = 'hello how are you?'
first = text[:text.find(' ')]
last = text[text.rfind(' ') + 1:]
Be aware, this has a lot of problems with edge cases (empty string, one word, etc)
Upvotes: 0
Reputation: 41
You can use .split and pop to retrieve the words from a string. use "0" to get the first word and "-1" for the last word.
string = str(input())
print(string.split().pop(0))
print(string.split().pop(-1))
Upvotes: 4
Reputation: 13334
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.']
Upvotes: 2
Reputation: 48067
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()
Upvotes: 56
Reputation: 4367
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
.
Upvotes: 24
Reputation: 2929
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']
Upvotes: 5
Reputation: 231
Let's say x
is your input. Then you may do:
x.partition(' ')[0]
x.partition(' ')[-1]
Upvotes: 8