Parsing numbers in Python

i want to take inputs like this 10 12

13 14

15 16

..

how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline


Asked by: Luke508 | Posted: 06-12-2021






Answer 1

I'm not sure I understood your problem very well, it seems you want to parse two int separated from a 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 press enter) and returns 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 have now '10 12', the two int are separated by a space, we split the string at the space with

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

now you have a list of strings, you want to convert them in int, so:

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

then you assign each member of the list to a variable (a and b) and then you do the product a*b

Answered by: Kellan739 | Posted: 07-01-2022



Answer 2

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

Answered by: David623 | Posted: 07-01-2022



Answer 3

You could use regular expressions (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)

Answered by: Maddie337 | Posted: 07-01-2022



Similar questions

python sax parsing big float numbers

Ok here's the story. I save big float numbers in an xml file. for example 0.016780745002189634. Numbers are saved correctly in file but when i parse the xml and i read them , some of them , (i pressume the largest ones) sax breaks them into two different numbers. Like: 0.016780 and 745002189634 . I am using utf-8 encoding if it has something to do, tried also iso same problem with different results thought. Thanks in advan...


python - Parsing Tabbed Numbers on a Line

I have a text file with a bunch of lines of series of numbers, resembling this format: 1 80,982 163,8164 170,2620 145,648 200,8021 173,2069 92,647 26,4122 140,546 11,1913 160,6461 27,7905 40,9047 150,2183 61,9146 159,7420 198,1724 114,508 104,6647 30,4612 99,2367 138,7896 169,8700 49,2437 125,2909 117,2597 55,6399 I'd like to create a nested dic...


Parsing Text Files with Python 3, Regex and Random Numbers

Here is the input text file I am working with: https://gist.github.com/TestAcc7777/5983147 In the text file, each line after the initial few contains 'CORE X', where X is a number from 1 to 64. Some of the lines containing 'CORE X' also contain either 'V3' or 'V4. For each value of X, I want to output the lines containing 'CORE X' and...


python - Parsing lines with numbers and words

I have a file to parse and I don't know which is the best strategy to make the regular expression. I want to obtain the line where de data is. (I already made to get the data I want from lines, but I realised I left behind some matches because my first regular expression it is not good.) Here is some of the regular expressions/strategies I tried: Find the heading and match everything below until tw...


python - Parsing different numbers with RegEx

Is it possible to parse all of the "weights" from the two emails below? I need a RegEx powerful enough to capture only the "weights" from these two emails, and 100's of more emails. The RegEx I'm using now searches for commas and takes the numbers on either side of them, which is perfect for weights in the thousands, but fails to capture weights below one thousand, such as the 954lbs and 800lbs va...


python - Parsing numbers into two 2D arrays from file

I have this in a file: 1 0 2 4 3 4 6 5 2 1 4 4 5 2 1 5 6 8 5 3 - 3 2 4 0 3 2 4 2 0 7 3 3 3 3 0 2 1 3 2 2 I need to split each one into its own matrix when the line is '-'. What I have done so far: with open(fname) as f: content = f.readlines() subArray = [] firstMatrix= [] for line in content: if line.strip() == ...


python - Parsing broken XML with numbers as tag names

I have lots of xml files that have keys that are in digit format i.e <12345>Golly</12345> When parsing using ElementTree I get an error not well-formed (invalid token). I am assuming this because the keys are in digit format and not words. When I try to change/replace the keys into string by adding double quotes using regex xmlstr = re.sub('<([...


python - Parsing Large Numbers

I am writing some simple code to raise a base value to a power then perform some operations on the output. I have included the code I am using now, below ( see end of this message ), also see immediately below what this looks like when I run my script from the console : ......................................... C:\PYTHON34>python tst.py INPUT Value: 431.1 INPUT Power Value; 1.9907 RESULT 1739.55...


python - Parsing a set of range of numbers

I wrote a simple code to find the intersection between two set of ranges and print the intersection. Now i am trying to write the result to a file. but i get an error saying write() argument must be str not set. import numpy # initialize A and B filename = "set.txt" f = open("set.txt", "w") x = numpy.arange(4000, 5000, 1) y = numpy.arange(3500, 5500, 1) #x.intersection(y) #print (set(x).intersection(y))...


Python parsing custom commad that adds 2 numbers

I'm trying to make a basic command line in python. I have a user input that I am spliting into a dictionary (called tokens) I want to take values from the dictaionary and add them together. Here's the code: userInput = input(': ') tokens = userInput.split() #sets tokens as a dict, where word 1 is 0:, word 2 is 1:, etc command = tokens[0] #first word of cmd args = tokens[1:] #second wor...


python - Parsing numbers of integer and real type in string

I have got a list of strings of the following format: [ "%AB0.1.100", "%TB4.1.15" ] How i can parse this strings, that a i'd like to take for 1st element of list "0.1" of real type and "100" of integer type and "4.1" of real type and "15" of integer type. How i can do this in loop ?


python sax parsing big float numbers

Ok here's the story. I save big float numbers in an xml file. for example 0.016780745002189634. Numbers are saved correctly in file but when i parse the xml and i read them , some of them , (i pressume the largest ones) sax breaks them into two different numbers. Like: 0.016780 and 745002189634 . I am using utf-8 encoding if it has something to do, tried also iso same problem with different results thought. Thanks in advan...


python - Parsing Tabbed Numbers on a Line

I have a text file with a bunch of lines of series of numbers, resembling this format: 1 80,982 163,8164 170,2620 145,648 200,8021 173,2069 92,647 26,4122 140,546 11,1913 160,6461 27,7905 40,9047 150,2183 61,9146 159,7420 198,1724 114,508 104,6647 30,4612 99,2367 138,7896 169,8700 49,2437 125,2909 117,2597 55,6399 I'd like to create a nested dic...


Parsing Text Files with Python 3, Regex and Random Numbers

Here is the input text file I am working with: https://gist.github.com/TestAcc7777/5983147 In the text file, each line after the initial few contains 'CORE X', where X is a number from 1 to 64. Some of the lines containing 'CORE X' also contain either 'V3' or 'V4. For each value of X, I want to output the lines containing 'CORE X' and...


python - Parsing lines with numbers and words

I have a file to parse and I don't know which is the best strategy to make the regular expression. I want to obtain the line where de data is. (I already made to get the data I want from lines, but I realised I left behind some matches because my first regular expression it is not good.) Here is some of the regular expressions/strategies I tried: Find the heading and match everything below until tw...


parsing - Create a list of numbers that exist in a file with Python

I have a file with a list of words and numbers. What I want to do is create a list of numbers between 0 and that are not contained within this file. I have tried to the following to no avail: #!/usr/bin/python import sys PATH_TO_FILE = "C:\\Path\\To\\My\\File" file = open( PATH_TO_FILE, "r") open_numbers = list(range(0,10500)) used_numbers = [] for lines in file.readlines(): lines = lines.r...


parsing - Why can't I scrape numbers over 999,999? (XPaths in Python)

I am trying to scrape the number of travelers to foreign countries from a site (link in code). For some reason when I actually get the data displayed it ignores any number over 999,999. Maybe someone can spot what I'm missing here. import requests from lxml import html import csv import pandas as pd import re r = requests.get('http://data.worldbank.org/indicator/ST.INT.ARVL/countrie...


Parsing numbers into point objects in Python

I need to get an input line from the user. It must be a series of numbers separated by spaces. I need to parse the input into a series of Point objects. The points are like points on a Cartesian plain (x, y). And finally I have to print those point out like (1, 2), (3, 4), (5, 6), etc. If the input is "0 1 2 3 4 5" the output should be (0, 1), (2, ...


python - Parsing different numbers with RegEx

Is it possible to parse all of the "weights" from the two emails below? I need a RegEx powerful enough to capture only the "weights" from these two emails, and 100's of more emails. The RegEx I'm using now searches for commas and takes the numbers on either side of them, which is perfect for weights in the thousands, but fails to capture weights below one thousand, such as the 954lbs and 800lbs va...


python - Parsing numbers into two 2D arrays from file

I have this in a file: 1 0 2 4 3 4 6 5 2 1 4 4 5 2 1 5 6 8 5 3 - 3 2 4 0 3 2 4 2 0 7 3 3 3 3 0 2 1 3 2 2 I need to split each one into its own matrix when the line is '-'. What I have done so far: with open(fname) as f: content = f.readlines() subArray = [] firstMatrix= [] for line in content: if line.strip() == ...


Any python libs for parsing apache config files?

Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)? As i'll be able to rewrite them in python.


Any python libs for parsing Bind zone files?

Any python libs for parsing Bind zone files? Basically something that will aid in adding/removing zones and records. This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution.


Parsing a file with column data in Python

I have a file that contains the symbol table details.Its in the form of rows and columns. I need to extract first and last column. How can I do that?


parsing - How does one parse simple inline markup (i.e. *bold*), in Python?

How does one implement a parser (in Python) for a subset of wikitext that modifies text, namely: *bold*, /italics/, _underline_ I'm converting it to LaTeX, so the conversion is from: Hello, *world*! Let's /go/. to: Hello \textbf{world}! Let's \textit{go}. Though there's nothing specific about it being a conversion to LaTe...


regex - Python parsing

I'm trying to parse the title tag in an RSS 2.0 feed into three different variables for each entry in that feed. Using ElementTree I've already parsed the RSS so that I can print each title [minus the trailing )] with the code below: feed = getfeed("http://www.tourfilter.com/dallas/rss/by_concert_date") for item in feed: print repr(item.title[0:-1]) ...


Parsing HTML in Python

Closed. This question does not meet Stack Overflow guid...


Python regex parsing

I have an array of strings in python which each string in the array looking something like this: <r n="Foo Bar" t="5" s="10" l="25"/> I have been searching around for a while and the best thing I could find is attempting to modify a HTML hyperlink regex into something that will fit my needs. But not really knowing much regex stuff I havent had anything work yet. This is what...


parsing in python

I have following string adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0 I need only the value of adId,siteId and userId. means 4028cb901dd9720a011e1160afbc01a3 8a8ee4f720e6beb70120e6d8e08b0002 5082a05c-015e-4266-9874-5dc6262da3e0 all the 3 in different variable or in a array so that i can use all three...


python - Parsing HTML rows into CSV

First off the html row looks like this: <tr class="evenColor"> blahblah TheTextIneed blahblah and ends with </tr> I would show the real html but I am sorry to say don't know how to block it. feels shame Using BeautifulSoup (Python) or any other recommended Screen Scraping/Parsing method I would like to output about 1200 .htm files in the same directory into a ...


Expat parsing in python 3

import xml.parsers.expat def start_element(name, attrs): print('Start element:', name, attrs) def end_element(name): print('End element:', name) def character_data(data): print('Character data: %s' % data) parser = xml.parsers.expat.ParserCreate() parser.StartElementHandler = start_element parser.EndElementHandler = end_element parser.CharacterDataHandler = character_data parser.ParseFile(open('samp...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top