Algorithmsstring input reading

String Input Reading (stdin, strip, split)

TT
Testlaa Team
May 14, 20261 min read

Reading string input covers stripping whitespace, splitting fields, handling multiple lines, and choosing delimiters. Competitive platforms often give sys.stdin.read() or line loops—normalize line endings early.

Why this shows up in the real world

CLI tools parse argv and stdin text. Web forms send strings that you split and validate server-side.

Core idea (explained for students)

Typical flow: data = sys.stdin.read().strip(), then lines = data.splitlines(), then parse each line with split() or unpacking. For known arity, a, b = line.split().

Try this in Python

def parse_two_ints(line: str) -> tuple[int, int]:
    a, b = line.split()
    return int(a), int(b)


print(parse_two_ints("3   14"))

Common mistakes

  • Trailing newline-only inputs becoming empty after strip() when you still need one empty case.
  • split() maxsplit forgetting when there are extra spaces inside fields.

Key takeaways

  • Wrap parsing in small functions (parse_int_line) so main logic stays clean.
  • Log repr(line) when debugging invisible characters.

Tags:

StringsPythonStudents