Parsing numbers in Python

I want to accept input like this 10 12

13 14

15 16

..

how to take this input as two different numbers so that i can multiply them by python after every 10 and 12 a newline character appears

+2
source share
3 answers

I'm not sure that I understood your problem well, it seems you want to parse two ints separated from space.

In python you do:

s = raw_input('Insert 2 integers separated by a space: ')
a,b = [int(i) for i in s.split(' ')]
print a*b

Explanation:

s = raw_input('Insert 2 integers separated by a space: ')

raw_input takes everything you type (until you hit enter) and return it as a string, so:

>>> raw_input('Insert 2 integers separated by a space: ')
Insert 2 integers separated by a space: 10 12
'10 12'

In s you are now "10 12", two ints are separated by a space, we split the string in space using

>>> s.split(' ')
['10', '12']

now you have a list of strings you want to convert to int, therefore:

>>> [int(i) for i in s.split(' ')]
[10, 12]

(a b), a * b

+7
f = open('inputfile.txt')
for line in f.readlines():
    # the next line is equivalent to:
    # s1, s2 = line.split(' ')
    # a = int(s1)
    # b = int(s2)
    a, b = map(int, line.split(' '))
    print a*b
+2

(re -module)

import re

test = "10 11\n12 13" # Get this input from the files or the console

matches = re.findall(r"(\d+)\s*(\d+)", test)
products = [ int(a) * int(b)  for a, b in matches ]

# Process data
print(products)
0

Source: https://habr.com/ru/post/1629262/


All Articles