当行以句号字符结束时,如何结束程序?



如何结束逐行读取输入的程序,并在有句号时结束(空格无关紧要)?

例如:

input = "HI
bye
."

程序应在达到周期后结束。

我试着做两件事:

if line == ".":
break
if "." in line:
break

但是第一个不考虑空格,第二个不考虑";如2.1.

if line.replace(" ", "")[-1] == ".":
break

.replace(";", ")删除所有空格,[-1]取字符串

的最后一个字符。

您需要.strip()删除空格并使用.endswith()检查结束字符:

for line in f:
if line.strip().endswith("."):
terminate...

有一个名为endswith的字符串方法,但老实说我会检查字符串是否以'结束。'通过索引。

if my_str[-1] == '.':
do_something()

但是这也取决于你的字符串是如何被接收的。它真的来自input吗?是来自文件吗?您可能需要根据具体情况添加一些其他内容

几点说明:

  • 如果你想包含多行字符串
  • 你应该使用双引号
  • 我假设你想逐行检查输入,而不是一次检查所有
  • 不要使用关键字和内置和标准(或其他已经定义的)名称作为名称,这称为遮蔽

你可能想要的是:

from io import StringIO
# you need triple double quotes to have a multiline string like this
# also, don't name it `input`, that shadows the `input()` function
text = """HI
bye
."""
for line in StringIO(text):
if line.strip()[-1] == ".":
print('found the end')
break

请注意,StringIO的东西只是在那里的text逐行。在回答你的问题时,重要的部分是if line.strip()[-1] == ".":

当您的文本看起来像这样时,此解决方案也适用,例如:

text = """HI
some words
bye.   """  # note the space at the end, and the word in front of the period

如果您想在确切的点处结束字符串,您可以尝试:

input = '''HI
bye
.
hello
bye'''
index = input.find('.') # gets the index of the dot
print(input[:index+1])

最新更新