[Tutor] The better Python approach

Tim Golden mail at timgolden.me.uk
Wed Jan 21 14:40:15 CET 2009


Robert Berman wrote:
> Given a string consisting of numbers separated by spaces such as '1234 
> 5678 1 233 476'. I can see I have two obvious choices to extract or 
> parse out the numbers. The first relying on iteration so that as I 
> search for a blank, I build a substring of all characters found before 
> the space and then, once the space is found, I can then use the int(n) 
> function to determine the number.  From my C++ background, that is the 
> approach that seems not only most natural but also most 
> efficient......but....the rules of Python are different and I easily see 
> that I can also search for the first blank, then using the character 
> count, I can use the slice operation to get the characters. Of even 
> further interest I see a string built-in function called split which, I 
> think, will return all the distinct character sub strings for me.
> 
> My question is what is the most correct python oriented solution for 
> extracting those substrings?

Correct? I don't know. Working; try this:

<code>
s = '1234 5678 1 233 476'
nums = [int (i) for i in s.split ()]
print nums

</code>

If you had some more sophisticated need (he says,
inventing requirements as he goes along) such as
pulling the numbers out of a string of mixed
numbers and letters, you could use a regular
expression:

<code>
import re

s = '1234 abc 5678 *** 1 233 xyz 476'
nums = [int (i) for i in re.findall ("\d+", s)]
print nums

</code>

TJG


More information about the Tutor mailing list