Home > Blockchain >  How to end a program when the line is equal a period
How to end a program when the line is equal a period

Time:11-15

How do I end a program that reads an input line by line and it ends when there's a period (whitespace doesn't matter)

Like for example:

input = "HI
         bye
              ."

the program should end after it reaches the period

I tried doing two things

if line == ".":
    break

if "." in line:
    break

but the first one doesn't take in consideration of whitespace, and the second one doesn't take in consideration of "." in numbers like 2.1

CodePudding user response:

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

.replace(" ", "") removes all white-spaces, and [-1] takes the last character of the string

CodePudding user response:

You need .strip() to remove whitespaces and check the ending character with .endswith():

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

CodePudding user response:

There is a method for strings called endswith, but honestly I would check if the string ends with a '.' through indexing.

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

But this also depends on how your string is received. Is it literally from an input? Is it from a file? You may need to add something additional per the circumstance

CodePudding user response:

A few remarks:

  • you should use triple double quotation marks if you want to literally include a multiline string
  • I'm assuming you want to go over the input line by line, not just all at once
  • don't use keywords and the names of builtin and standard (or other already defined) names as names, that's called shadowing

Here's what you might be after:

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

Note that the StringIO stuff is only there to go over text line by line. The important part, in answering your question, is if line.strip()[-1] == ".":

This solution also works when your text looks like this, for example:

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