Python program to get the first word Given a string the task it to find its first word with some rules:


The string can have points and commas
A word can start with a letter, a point or space
One word can contain one apostrophe and it stills being a valid one


For example:

assert first_word("Hello world") == "Hello"
assert first_word(" a word ") == "a"
assert first_word("don't touch it") == "don't"
assert first_word("greetings, friends") == "greetings"
assert first_word("... and so on ...") == "and"
assert first_word("hi") == "hi"
assert first_word("Hello.world") == "Hello"


The code:

def first_word(text: str) -&gt; str:
    """
        returns the first word in a given text.
    """
    text = re.sub("[^A-Za-z'\s.]",'',text)
    words = text.split()
    for word in words:
        for i in range(len(word)):
            if word[i].isalpha() or word[i] == "'":
                if i == len(word) - 1:
                    if word.find('.') != -1:
                        return word.split('.')[0]
                    else:
                        return word


How could we improve it?
You could make the code better (and shorter) by using regex to split any delimiters that occur in the string, for example, in Hello.world, the string (list form) would then be like ['', 'Hello', ''] (after splitting the first word from delimiters) and then you can access the first word from index [1] (always). Like this, 

import re
def first_word(s):
    return re.split(r"(\b[\w']+\b)(?:.+|$)", s)[1] 




Here are some tests:

tests = [
"Hello world",
"a word",
"don't touch it",
"greetings, friends",
"... and so on ...",
"hi",
"Hello.world",
"Hello.world blah"]

for test in tests:
    assert first_word("Hello world") == "Hello"
    assert first_word(" a word ") == "a"
    assert first_word("don't touch it") == "don't"
    assert first_word("greetings, friends") == "greetings"
    assert first_word("... and so on ...") == "and"
    assert first_word("hi") == "hi"
    assert first_word("Hello.world") == "Hello"
    assert first_word("Hello.world blah") == "Hello"
    print('{}'.format(first_word(test)))


(\b[\w']+\b)(?:.+|$) is used above, where (\b[\w']+\b) calls the first word of the string (in list form). \b allows you to perform a "whole words only" search using a regular expression in the form of \b"word"\b. Note that using [\w'] (instead of [\w+]) leaves the apostrophe in don't. For (?:.+|$), you can take a look here.

Here are the expected outputs:

Hello
a
don't
greetings
and
hi
Hello
Hello


After timing it - 

%timeit first_word(test)
&gt;&gt;&gt; 1.54 µs ± 17.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


NOTE - A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data streams. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values.

Hope this helps!