I have to write a single function that should return the first word in the following strings:
("Hello world") -> return "Hello"
(" a word ") -> return "a"
("don't touch it") -> return "don't"
("greetings, friends") -> return "greetings"
("... and so on ...") -> return "and"
("hi") -> return "hi"
All have to return the first word and as you can see some start with a whitespace, have apostrophes or end with commas.
I've used the following options:
return text.split()[0]
return re.split(r'\w*, text)[0]
Both error at some of the strings, so who can help me???
re.search(r'\w+', text).group()
? – cs95 Jan 4 '18 at 10:58don
instead ofdon't
;) Tryre.search('[\w\']+', s).group()
– DeepSpace Jan 4 '18 at 10:58r""""[^"\w]*([\w'-]+)"""
– Wiktor Stribiżew Jan 4 '18 at 11:00[\w']+
to find all word-constituents and apostrophes but that would quickly lead to a problem with an input like"'No!' he shouted"
('No
is probably not wanted). – Alfe Jan 4 '18 at 11:02