简体   繁体   中英

How to remove substring from the string entered through "stdin" in Python

Input: Input consists of many lines. At the end of each line, there is a hash symbol #. For example:

1st line# 
2nd line# 
3rd line#
Output expected:
1st line 
2nd line
3rd line

You have loop when never will finish.. I don't see the need of while in your case.

  import sys
    for line in sys.stdin:
        line = line.replace('#', '')
        print(line)
import sys
for line in sys.stdin:
    print(line)

when this code is used, a new line character is appended internally to the line. so first we can strip it using the rstrip(). Since the requirement is only to remove a '#' present as the last letter of the line, we can simply slice it.

import sys
for line in sys.stdin:
    print(line.rstrip()[:-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM