What Is Wrong with My Code for Codehs 8.3.7: Exlamat! on Po! Nts?
This Is What I'm Supposed to Do: Words Are Way More Fun When You Replace the Letter ‘I’ with an Exclamation Point! Write a Program That Asks the User for a...
This is what I'm supposed to do: Words are way more fun when you replace the letter ‘i’ with an exclamation point!
Write a program that asks the user for a string and then prints the same string with every lowercase i replaced with an exclamation point. Your program should:
Convert the initial string to a list
Use a for loop to go through your list element by element
Whenever you see a lowercase i, replace it with an exclamation point in the list
Print the stringified version of the list when your for loop is finished
Here’s what an example run of your program might look like:
Enter text: I like music.
I l!ke mus!c.
This is my code right now:
my_string = input("Enter text: ")
my_list = list(my_string)
for item in my_list:
if item == "i":
print "!"
my_list.remove("i")
print item
(" ").join(my_list)
The problem with my code is that instead of replacing i with !, it adds the !, keeps the i and removes the letter after i. How do I fix my code?
2 Answers
You may want to leverage enumerate() to change list items:
my_string = list(input('Enter string: '))
for i, char in enumerate(my_string):
if char == 'i':
my_string[i] == '!'
print(''.join(my_string))
It is usually not the best to remove list items during iteration, but this approach keeps track of what item we’re at and we can edit it using the list index, i.
Better yet, use a list comprehension and a ternary if statement:
my_string = list(input('Enter text: '))
my_string = ['!' if char == 'i' else char
for char in my_string]
print(''.join(my_string))
Entering the if clause does not prevent the 'i' from being printed.
Imagine the scenario where item == 'i'. It will match the if clause and proceed to printing '!' and removing an 'i' from my_list. However. item is still 'i', and will be printed by print item
You could modify the code to print item only when it's not an i.
my_string = input("Enter text: ")
my_list = list(my_string)
for item in my_list:
if item == "i":
print "!"
my_list.remove("i")
else:
print item
(" ").join(my_list)
Better yet, if you don't need to save my_list for posterity, you don't even need to remove 'i' characters from my_list. So you could probably live without the following lines.
my_list.remove("i")
and
(" ").join(my_list)