My automated tests contains a lot of string manipulations. I do exercise a lot with programming. In this post I will solve a problem to distinguish between words and numbers. I will see if I can search for three words in python strings.
I have a question for you. Solve the following problem.
The input value is a string with words and numbers. One space separates the words and numbers in the string. The words contains only letters. You should check if the string contains three words in succession.
For example, the string “start 5 one two three 7 end” contains three words in succession.
three_words("Hello World hello") == True three_words("He is 123 man") == False three_words("1 2 3 4") == False three_words("one two three four") == True three_words("Hi") == False
A possible solution
I start with splitting the input string. The input string contains words separated with spaces. Splitting is not a problem in python.
I can process all items in the list with a list comprehension. I need to determine if a list item is a number or a string. First I tried with this code:
[isinstance(x, str) for x in words.split()]
It seems a good solution. I check if it is a string. All chunks are strings ! The input string is already a string. Splitting it in chunks results in a list of strings. This solution is not correct for numbers and never returns a False value.
I found in the a string method isdigit in the documentation.
This is what I want! I will check if the chunks are digits.
[x.isdigit() for x in words.split()]
The result is now a list of booleans. The only thing that rest is to check if in the list 3 positions in succession values are False. I can do that by converting the items back to a string. First I convert all the items to a string. Then I merge the list back to one string.
"".join([str(x.isdigit()) for x in words.split()])
This string contains only True and False. The check if the string contains three words in succession is simple. Just check if the string “FalseFalseFalse” is in the string. This results in my solution. I can search for three words in python strings !
def three_words(words): words = "".join([str(x.isdigit()) for words in s.split()]) return "FalseFalseFalse" in words
The isdigit method can be used to check is a string is a number. With that method and a list comprehension it is easy to check for three words in a python string. The problem I solved can be used in replies from API calls. I can use it to see if a string is a number or not.