0

I am working with user input in my code, but need to make certain conditions to run the programme. The user needs to enter a sentence with all vowels censored with an asterisk. I want to then check if they accidentally entered vowels too, eg. h*llo is not good. I tried the following:

for x in inputword:
    if x == 'a' or 'e' or 'i' or 'o' or 'u':
        print('Enter a sentence with no vowels')
        return

The problem is, if they now enter h**ll* or something that should be okay, the code above still gets triggered.... how to fix this?

  • 2
    Does this answer your question? [How to test multiple variables against a single value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-single-value) – CrazyChucky Apr 29 '21 at 15:36

3 Answers3

0

I think you have misunderstood how the 'or' works. Try this:

word = 'Hello'


def func(word):
    word2 = []
    for letter in word.lower():  # <-- Using word.lower() to make eveything lowercase and easier to use
        if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
            word2.append('*')
        else:
            word2.append(letter)
    return word2


print(func(word))

Here we can just iterate through the word and replace it with an '*' if the letter is a vowel.

Another method is to have a list of vowels, and if the letter we iterating through (from the word) is in our vowel list, we can replace with an '*'

word = 'Hello'


def func(word):
    word2 = []
    vowels = ['a', 'e', 'i', 'o', 'u']
    for letter in word.lower():  # <-- Using word.lower() to make eveything lowercase and easier to use
        if letter in vowels:
            word2.append('*')
        else:
            word2.append(letter)
    return word2


print(func(word))
Dugbug
  • 454
  • 2
  • 11
  • 1
    The op never wanted to replace the input with asterics!! All he said he want is letters like ```h**ll*``` without any vowel – Mab Apr 29 '21 at 15:58
0

This code will check if a string contains a vowel:

def contains_vowels(s):
    vowels = ["A", "E", "I", "O", "U"]
    matched = [char in vowels for char in s.upper()]
    return any(matched)

Test:

contains_vowels("hey")
Out[82]: True

contains_vowels("h*y")
Out[83]: False
Tom McLean
  • 5,583
  • 1
  • 11
  • 36
0

The problem here is Python conditional Test doesn't work the way you're assuming.

Non empty strings are evaluated as true. So your code looks like below

if ( x== 'a') or  'e' or 'i' or 'o' or 'u':

Easiest way to achieve your aim is

vowels = {'a','e','i','o','u'}
if(x in vowels):
Mab
  • 412
  • 3
  • 12