Would anyone be able to tell me why the given solution to this problem works? In an earlier lesson we learned that strings are immutable. It seems like the process of iterating through the letters in the given word and then adding every other one to the string every_other would necessarily require us to change the string every_other.
Is it that strings can be added to, but the individual characters in strings can’t be removed or swapped without creating a new string?
It would seem that way, although we are not changing it, but replacing it with a new composed string value
Only when we do it on the right side of an assignment (or in an argument) using concatenation (or other method) to build the desired string expression. Each time we assign it to the left side. If that is the same variable, then we have replaced its value with the new one.
if a and b are string values,
a = a + b
replaces a with the joint string value. The right hand side is not mutating a string, but creating a single string value.
a += b
says the same thing using the compact assignment operator.
Your function prints something then exits. Then the commands print again only there is nothing to print but what comes back from print(), which is None. This is why we do not print inside a function. It makes the result useless to the outside (the program).
Thanks for the explanation. I realize I don’t know how exactly the commands would be excuted. So I wonder in my wrong code, the for loop commands print(printed)? and then the def functions commands to print(printed) again? That’s why the second time its output is None, am I right? I am a bit confused regarding the indentation and its relations with the commands or in this case print is commanded again by def function?
Thanks for liking my post and I get “welcome” Badge from it^^
Thank you again for your reply. I always enjoy reading them.
P.S. I don’t always point out typo/error unless I am not sure about the exact intention/meaning of it.
# Write your every_other_letter function here:
def every_other_letter(word):
new_str = ''
for i in range(len(word) - 1):
if i% 2 == 0:
new_str+= word[i]
return new_str
# Uncomment these function calls to test your function:
print(every_other_letter("Codecademy"))
# should print Cdcdm
print(every_other_letter("Hello world!"))
# should print Hlowrd
print(every_other_letter(""))
# should print