'Python Function keeps returing none [closed]
I have a function that replaces all vowels when shown below, but when i go to use the function and print the output result, i get none
def replace_vowels(name):
name.lower
name.replace("a","*")
name.replace("e","*")
name.replace("i","*")
name.replace("o","*")
name.replace("u","*")
name.replace("y","*")
celeb_1 = input("Enter the name of the first celeberty: ")
celeb_2 = input("Enter the name of the second celeberty: ")
celeb_3 = input("Enter the name of the third celeberty: ")
celeb_1_s = replace_vowels(celeb_1)
celeb_2_s = replace_vowels(celeb_2)
celeb_3_s = replace_vowels(celeb_2)
print (celeb_1_s)
print (celeb_2_s)
print (celeb_3_s)
The output result is:
Enter the name of the first celeberty: Elon Musk
Enter the name of the second celeberty: Donald Trump
Enter the name of the third celeberty: Bill Gates
None
None
None
Solution 1:[1]
You need to return the result of calling lower and replace; these don't mutate the string (strings are immutable). Chaining all the calls together it would look like:
def replace_vowels(name):
return name.lower().replace(
"a", "*"
).replace(
"e", "*"
).replace(
"i", "*"
).replace(
"o", "*"
).replace(
"u", "*"
).replace(
"y", "*"
)
Or you could re-assign each call's result to name and return it at the end:
def replace_vowels(name):
name = name.replace("a","*")
name = name.replace("e","*")
name = name.replace("i","*")
name = name.replace("o","*")
name = name.replace("u","*")
name = name.replace("y","*")
return name.lower()
Or use an iteration instead of six calls to replace:
def replace_vowels(name):
return ''.join("*" if c in "aeiouy" else c for c in name.lower())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
