0

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.

1
  • [int(row.split()[0]) for row in data.split('\n')] is one way to do this. Commented Nov 1, 2016 at 20:49

3 Answers 3

1

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()]
Sign up to request clarification or add additional context in comments.

2 Comments

oh gosh, I've been on code golf too much, i almost commented saying "-1 byte if you remove the whitespace before for"
Thanks so much. Worked like a charm!
0
y = [int(x) for x in data.split() if x.isdigit() and int(x) > 99999]
y.sort()

will return a list of ALL numbers in that string as ints that consist of 6 digits

edit: not return, but rather y will be assigned, and then sorted =D so really, y will be a list of all integers in that string which consist of 6 digits

2 Comments

for d in data.split('\n'):
OP wants the first number in each string and turned into a number
0

Another short solution to get the number at the beginning of each line by using re.findall function (from re module) with re.MULTILINE flag:

import re

# your 'data' with text

print(re.findall(r'^\d+\b', data, flags=re.MULTILINE))

The output:

['456432', '345903', '456432']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.