Hello I am a C# programmer but I think it's good to learn python too so I am learning python I have this code
def disemvowel(string_):
for n in string_:
if(n is 'a' or 'e' or 'u' or 'o' or 'i'):
string_ = string_.replace('n' , '')
return string_
print(disemvowel('Hello'))
I declared a function that removes vowels from a string I searched its problems but I couldn't find anything I even passed the return value of the replace function to string and then pass it what is my code problem ? thanks for you answers
CodePudding user response:
is
is used to compare the ID's. In your case, it is not necessary that n and "a" have same memory location. You can change it to ==
to compare the VALUES. If the value of n is "a" then n=="a" should return True
. is
will return True
when the location of both will be same. It will return False
even if the value is correct. Or you can use in
as well. in
will return True
if the variable in present in a string or iterable datatypes. Your code would be:
- using
==
:
def disemvowel(string_):
for n in string_:
if n.lower()=="a" or n.lower()=="e" or n.lower()=="i" or n.lower()=="o" or n.lower()=="u":
string_ = string_.replace(n,'')
return string_
print(disemvowel('Hello'))
- using
in
def disemvowel(string_):
for n in string_:
if n.lower() in ["a","e","i","o","u"]:
string_ = string_.replace(n,'')
return string_
print(disemvowel('Hello'))
CodePudding user response:
try this:
def disemvowel(string_):
res = ''
for n in string_:
if n not in ['a' , 'e', 'u' ,'o' , 'i']:
res = n
return res
print(disemvowel('Hello'))
CodePudding user response:
def disemvowel(string_):
for n in string_:
if n in 'aeiouAEIOU':
string_ = string_.replace(n, '')
return string_
print(disemvowel('Hello'))
Output: 'Hll'
If you write if n in 'aeiouAEIOU'
you don't have to use all the or operators.