2012-09-01 220 views
0

我正在写一个程序,该程序应该按照输入行读取,直到输入空行。如果这条线开始与西蒙说,它应该打印出该行的其余部分。不以Simon开头的线应该被忽略。所以我无法写程序,因为它需要像这样的输出:Python语句打印错误

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: 

和我生产的代码是这样的:

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' 

回答

1
用伪

就像你几乎在那里,你只需要从输出中删除“Simon说”:

print word.replace('Simon says', '') 
1

看来:

word = raw_input("Enter: ") 
i = "" 
while word != i: 
    if 'Simon says' in word: 
     print word 
    word = raw_input("Enter: ") 
+0

丹尼尔有一个在输出 – rocker789

+0

来了一个空间@ rocker789是因为'replace'只替换你告诉它的子字符串,而不是紧接它后面的空格 - 如果你想摆脱这个空间并且把它包含在'replace'的调用中,就像'word'一样。取代('Simon说','')'。 – lvc

3

你的代码有两个问题:第一,你的if -condition会做细微的错误的事情 - 例如,

>>> 'hello, simon'.startswith('simon') 
False 
>>> 'simon' in 'hello, simon' 
True 

in测试如果一个子是任何地方字符串中。为了测试是否是在准确的开始,Python提供了方便叫startswith功能:

>>> 'simon'.startswith('s') 
True 

你唯一的另一个问题是,目前,你将打印出整个输入字符串,包括“西蒙说” ,你想要删除。除去它的最简单的方法是使用str.replace

>>> 'simon says'.replace('simon', 'fred') 
'fred says' 

并与空字符串('')更换将有效去除串。但是,这一次有同样的问题 - 它会做字符串替换任何地方

>>> 'simon says lets play simon says'.replace('simon says', '') 
' lets play ' 

但你可以告诉它最多只有一个更换 - 既然你已经知道了字符串以“西蒙说”,你就知道这将是一个在开始:

>>> 'simon says lets play simon says'.replace('simon says', '', 1) 
' lets play simon says' 

你可以,或者,使用字符切片 - 'fred'[2:]询问的'fred'(所以第二个字符后开始串,从‘E’ ),并且直到结束:

>>> 'fred'[2:] 
'ed' 

“西蒙说”有10个字母,因此:word[10:]将在word之后。但是,这也容易导致微妙的错误,如果你计数错误的字母数 - 避免这种情况,你可以让Python为你做它,如:

word[len('Simon says'):]