Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialeric93
625 PointsDevowel a string.
I have a question regarding this code. My aim is to remove all vowels from a string:
# 'California' is the_word I'm removing vowels from
the_word = "California"
# a for-loop that will look over and remove any vowels
for vowel in 'aeiou':
# Assign the expression to an existing variable. Why?
the_word = the_word.replace(vowel, '')
# print the output
print(the_word)
This program works if I reuse 'the_word' variable with a new expression in my for-loop. However, if I choose to use a new variable (ie, 'new_word') in my for-loop it doesn't work. For example:
the_word = "California"
for vowel in 'aeiou':
new_word = the_word.replace(vowel, '')
print(new_word)
It may be a silly question, but, why do I have to use the existing variable instead of a new one?
1 Answer
pala
15,913 PointsHi, because when you use the same variable "the_word", it would change when every loop.
So you can get what you want.
When you use new variable "new_word", now you have two variable,
but eveytime "the_word" variable is still the same mean "California".
The changes is happen in "new_word".
First loop, you pass "the_word" mean "California", then "new_word" will get "Californi".
Second loop, because "the_word" is still "California", so you pass it in, then you get "new_word" point to "California".
Because you don't print it out, you will only see the last loop resault.
the_word = "California"
for vowel in 'aeiou':
new_word = the_word.replace(vowel, '') # here
print(new_word) # We get "California", in last loop,"u" didn't replace any word.
try this code, and I think you will know what I mean :)
the_word = "California"
for vowel in 'aeiou':
new_word = the_word.replace(vowel, '')
print("now replace:" + vowel) # print every loop's resault
print("new_word:" + new_word)
print("the_word:" + the_word)
print("------")