Python语句打印

2024-05-14 19:39:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,它应该读入输入行,直到输入一个空行为止。如果这行以Simon开头,它应该打印出该行的其余部分。不以Simon says开头的行应该被忽略。所以我无法编写程序,因为它需要这样输出:

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:

我的代码是:

^{pr2}$

Tags: 程序yourlikeshoutentersimonsays编写程序
3条回答

看起来你就快到了,你只需要从输出中删除“Simon says”:

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

伪代码:

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'

您的代码有两个问题:首先,您的if-条件将微妙地执行错误的操作-例如

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

in测试子字符串是否在字符串中的任何位置。为了测试它是否正好在开始时,Python提供了一个方便地称为startswith的函数:

^{pr2}$

您唯一的另一个问题是,当前,您将打印出整个输入字符串,包括要删除的“Simon says”。最简单的方法是使用str.replace

^{3}$

而替换为空字符串('')将有效地删除子字符串。但这也有同样的问题-它将在字符串中的任何地方替换

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

但是你可以告诉它最多只替换一个,因为你已经知道字符串以“Simon says”开头,所以你知道它将是开头的那个:

>>> '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'):]

相关问题 更多 >

    热门问题