Nadim Zaidi Nadim Zaidi - 1 year ago 124
Python Question

How to loop through multiple lines in a python string and convert to integers:

I am attempting to cycle through the following code:

data = "456432 jfhjsdfjs fhdjsjk 990 fdjsf"
345903 fdsfdfs fsfdsfd 667 fsdfd
456432 sfdsfds fdsfdsfd 778 fdsfds"

I want to convert the numbers of the first series of numbers of each line so it returns the following (converted to integers)

Here is the code I have so far, which sorts everything:

print [int(data.split()[0])]

I am guessing I will have to loop through each line while still pulling the 0 item of the list of each line. Though not sure I am on the best workflow for this.

Answer Source

You have to iterate line by line, and then do split()[0] to get the first value:

[int(line.split()[0]) for line in data.splitlines()]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download