soup
soup

Reputation: 101

How to ignore the enter key/ treat it as the space key in Python?

So I want the user to enter a matrix in the form, for example:

 2 2
 3 4

I need Python to ignore the enter key here and treat it the same as the space bar, otherwise it would give me an error when I press the enter key after last number in the first row, making it only possible to enter the matrix as:

2 2 3 4

Is it possible?

Upvotes: 0

Views: 391

Answers (1)

wjandrea
wjandrea

Reputation: 32964

If you want the user to input multiple lines, you can't just ignore a newline; instead you'll have to take multiple lines of input. See How do I read multiple lines of raw input in Python?

For example, based on jamylak's answer:

matrix = []
for line in iter(input, ''):
    matrix.append([int(x) for x in line.split()])

for x in matrix:
    print(x)

Input (note the blank line at the end):

2 3
3 4

Output:

[2, 3]
[3, 4]

Upvotes: 1

Related Questions