Reputation: 259
I am Writing a program that should read in lines of input until a blank line is entered. If the line starts with Simon says it should print out the rest of the line. Lines that do not start with Simon says should be ignored. So I unable to write the program as it requires to output like this:
Enter: jump
Enter: Simon says shout loudly
shout loudly
Enter: simon would like you to eat a frog
Enter: Simon says clap your hands
clap your hands
Enter:
And the code which I am producing is this:
word = raw_input("Enter: ")
i = ""
while word != i:
if 'Simon says' in word:
print word
word = raw_input("Enter: ")
Upvotes: 0
Views: 298
Reputation: 35059
Your code has two issues: first, your if
-condition will do subtly the wrong thing - eg,
>>> 'hello, simon'.startswith('simon')
False
>>> 'simon' in 'hello, simon'
True
in
tests if a substring is anywhere in the string. To test if it is at exactly the start, Python provides a function conveniently called startswith
:
>>> 'simon'.startswith('s')
True
Your only other problem is that currently, you will print out the entire input string, including the "Simon says", which you want to remove. The easiest way to remove it is to use str.replace
:
>>> 'simon says'.replace('simon', 'fred')
'fred says'
And replacing with the empty string (''
) will effectively remove the substring. But this has the same problem again - it will do the replacing anywhere in the string:
>>> 'simon says lets play simon says'.replace('simon says', '')
' lets play '
But you can tell it to only replace at most one - and since you already know the string starts with "Simon says", you know that will be the one at the start:
>>> 'simon says lets play simon says'.replace('simon says', '', 1)
' lets play simon says'
You could, alternately, use string slicing - 'fred'[2:]
asks for the string starting after the second character of 'fred'
(so, from the 'e'), and going till the end:
>>> 'fred'[2:]
'ed'
"Simon says" has 10 letters, so: word[10:]
will be everything in word
after that. But this can easily lead to subtle bugs if you miscount the number of letters - to avoid that, you could get Python to do it for you, as in:
word[len('Simon says'):]
Upvotes: 3
Reputation: 599450
Seems like you're almost there, you just need to remove "Simon says" from the output:
print word.replace('Simon says', '')
Upvotes: 1
Reputation: 214949
in pseudocode:
forever (while True) do the following:
input a sentence
if its length is 0: break
else if it starts with 'Simon says':
print sentence from the n-th character (sentence[n:]),
where n is the length of the string 'Simon says'
Upvotes: 1