Uche
Uche

Reputation: 13

Python keeps treating empty string as character when compiling

def change(sentence):
    vowel = {'a':'1','e':'2','i':'3','o':'4','u':'5'}
    final_sentence = ''
   
    for s in sentence:
        s = s.lower()
        if s not in vowel:
            final_sentence = final_sentence + s + 'a'
        
        else:
            for v in vowel:
                if s == v:
                    s = vowel[v]
                    final_sentence += s
  
    
    return final_sentence

Hi all, above is my code. What i am trying to achieve is a simple game where a sentence is passed into a function and every vowel (a,e,i,o,u) found in the sentence should be replaced with corresponding numbers(1,2,3,4,5) and concatenated with my variable called final_sentence. ALso every consonant should be concatenated with the string 'a' and then concatenated with my final_sentence variable. Finally the final_sentence variable should be returned. The string is passed into the function was 'I love you' and the corresponding result should be "3 la4va2 ya45" but that is not the case. Apparently, python sees the empty strings between words as characters and is now concatenating the string 'a' to them. How do i stop that?

see my output below

'3 ala4va2 aya45'

Upvotes: 0

Views: 69

Answers (2)

alani
alani

Reputation: 13079

A space (" ") is a string, every bit as much as a letter. It is character number 32.

The following suggested replacement code relies on the fact that lower case letters appear consecutively in their ASCII representation, so that everything between "a" and "z" (inclusive) is one of the lower case letters.

def change(sentence):
    vowel = {'a':'1','e':'2','i':'3','o':'4','u':'5'}
    final_sentence = ''
   
    for s in sentence:
        s = s.lower()
        if s in vowel:  # lower case vowels
            for v in vowel:
                if s == v:
                    s = vowel[v]
                    final_sentence += s
        elif "a" <= s <= "z":   # all other lower case letters
            final_sentence += s + 'a'
        else:   # everything that is not one of the lower case letters
            final_sentence += s
            
    return final_sentence


print(change("I love you"))

Upvotes: 0

amiasato
amiasato

Reputation: 1020

Python doesn't "see empty strings as characters", but rather "sees characters as strings", as characters in Python are simply strings of length 1. The condition s not in vowel will evaluate to True whenever s is anything but the vowel keys from your dict, including the empty and single space string.

Therefore, a simple fix would be:

if s not in vowel and s != ' ':

Or even more generally, using the string.isalpha method:

if s not in vowel and s.isalpha():

Upvotes: 1

Related Questions