Ammar
Ammar

Reputation: 13

.isalpha() returns false on a specific example

In a given string you should reverse every word, but the words should stay in their places.

Input: A string.

Output: A string.

Precondition: The line consists only from alphabetical symbols and spaces.

def backward_string_by_word(text: str) -> str:
    # your code here
    word = str()
    for i in text:
        if i.isalpha():
            word += i
        else:
            text = text.replace(word,word[::-1])
            word = ''
        if i.isalpha() and text.index(i) == text.index(text[-1]):
            text = text.replace(word,word[::-1])
    return text

I'm still in elementary level so excuse my simple answers, I know there are much easier ways to solve this but I want to learn where the code I made is failing.

My approach The loop begins a string is created which adds characters until .isalpha() returns false. Then I replace the string within the original text and reset the string for the next word until the loop ends. This worked fine with the first 4 examples given to me; '', 'world', 'hello world', 'hello world'.

for some reason, in the fifth example 'welcome to a game', the code returned 'ewlcome ot a emag' instead of 'emoclew ot a emag'. Please help me understand what happened with the first word in the text.

Upvotes: 0

Views: 303

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19422

It fails because of your second check:

if i.isalpha() and text.index(i) == text.index(text[-1]):

Note that text[-1] is the last letter which is also e. But index returns the first index found so when i equals the first 'e', you have:

text.index(text[-1]) == text.index(i) == text.index('e') == 1

It would make more sense to do:

if i.isalpha() and text.index(i) == len(text)-1:

Which will also fail from the same reason (when actually reaching the last e, it will return 1). This check is simply not necessary. Just add the last replace outside the loop:

def backward_string_by_word(text: str) -> str:
    word = ''
    for char in text:
        if char.isalpha():
            word += char
        else:
            text = text.replace(word, word[::-1])
            word = ''

    return text.replace(word, word[::-1])

A simpler solution will be to split the string according to the words and reverse each one separately. split returns a list so we can enumerate it and join it back in the end:

def backward_string_by_word(text: str) -> str:
    words = text.split()
    for i, word in enumerate(words):
        words[i] = word[::-1]
    return ' '.join(words)

It can be even further reduced by creating a new list of reversed words:

def backward_string_by_word(text: str) -> str:
    return ' '.join(word[::-1] for word in text.split())

Upvotes: 1

Related Questions