0

I have the following code to read data

import sys

data = sys.stdin.readlines()
id = 0

while id < len(data) - 1:
    n = int(data[id])
    id += 1
    some_list = []
    for _ in range(n):
        x1, y1, x2, y2 = map(str, data[id].split(" "))
        some_list.append([x1, y1, x2, y2])
        id += 1
    print(some_list)

Input:

2
0 3 1 2
2 1 3 1
4
3 1 1 0
0 0 2 1
1 1 2 0
3 0 3 1

Its output:

[['0', '3', '1', '2\n'], ['2', '1', '3', '1\n']]
[['3', '1', '1', '0\n'], ['0', '0', '2', '1\n'], ['1', '1', '2', '0\n'], ['3', '0', '3', '1']]

You can see that "\n" is also written. How can I ignore "\n" (or remove it) without losing data read speed?

I need numbers to remain in string format. The construction sys.stdin.readlines() is also needed since I don't know how many lines (how many m-s) will be in the input.

wovano
  • 4,543
  • 5
  • 22
  • 49
niico
  • 57
  • 4
  • Does this answer your question? [Why doesn't calling a string method (such as .replace) modify (mutate) the string? Why doesn't it change unless I assign the result?](https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-string-method-such-as-replace-modify-mutate-the-strin) – aqua Nov 17 '22 at 19:45
  • Use `.split()` instead of `.split(" ")` – ritiek Nov 17 '22 at 19:48
  • Does this answer your question? [How to read a file without newlines?](https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines) – wovano Nov 17 '22 at 20:20
  • Instead of `sys.stdin.readlines()` use `sys.stdin.read().splitlines()` – wovano Nov 17 '22 at 20:21

1 Answers1

2

You may use rstrip from the string package.

For example here, just use:

y2.rstrip()

It will remove the \n at the end of y2 if there is one.

Asthom
  • 46
  • 3