wydncwymsjgcs
wydncwymsjgcs

Reputation: 69

extract the first letter of each word in a string

I'm new to python, thanks for anyone who will answer my question.

I'm trying to solve the question "Write a function takes a two-word string and returns True if both words begin with the same letter". The answer was like:

def animal_crackers(text):
   wordlist = text.split()
   return wordlist[0][0] == wordlist[1][0]
# Check 
animal_crackers('Levelheaded Llama')

But I want to use:

def animal_crackers(text):
    for word in text.split(): 
        if word[0][0]== word[1][0]:
            return True
        else:
            return False

My question is: Why does the for..in.. not work in this case? Doesn't the test.split() gives two separated word, so that I can use for to extract two words, and then use word[0][0]== word[1][0]to extract the first letter in each word?

Thanks for your help:)

Upvotes: 1

Views: 1786

Answers (3)

user16310106
user16310106

Reputation:

In the text.split(), it will return the two words and for-loop will iterate through the first word and then the second word. But in the first iteration, you will have only one word and by using word[0][0] and word[1][0], you only compare the first letter with the second letter of the same word. As a result, you will get always False.

Upvotes: 0

qkfsbxjayiedbe
qkfsbxjayiedbe

Reputation: 145

The problem with your code is that you are not accessing different words in your if-clause. The for-loop takes the first word in the wordlist and goes through the loop, when it is finished it takes the second word and goes through the loop again. So you can not just access a different word while inside the loop. What your code does instead is it compares the first two characters in each word.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

The problem with your current approach is that for word in text.split() will feed only one of the two words into each iteration of the loop. So it doesn't make sense to be considering each word in the loop as having two dimensions, because it only has a single dimension corresponding to the characters in each string. But in the correct answer your gave above, you want to compare both the first and last word at the same time.

By the way, there is also a fairly straightforward regex way of doing this:

def animal_crackers(text):
    if re.search(r'^(\w)\w* \1\w*$', text):
        return True
    else:
        return False

Upvotes: 2

Related Questions