Member Avatar for cyon

Given a coordinate string -- 'x, y' -- where x and y are 1-4 digits, separated by \D+:
'34, 58'

I want to able to get a tuple with each number as an integer:
(34 , 58)

Method 1: I could find the numbers, convert the tuple groups() to a list, convert the strings in that list to integers, then finally converting the list back to a tuple:

pattern = re.compile(r"(\d{1,4})\D+(\d{1,4})")
return tuple([ int(x) for x in list('34, 58').groups()) ])

Method 2: I could eliminate a tuple-to-list conversion with findall, but this method wouldn't be able to check if the coords are in the right format as the previous regex pattern:

pattern = re.compile('\d+')
return tuple([ int(x) for x in pattern.findall( '34, 58' )])

Method 3: Manually place each group() in a tuple

pattern = re.compile(r"(\d{1,4})\D+(\d{1,4})")
return ( int('34, 58').group(1)) , int('34, 58').group(2)) )

Is there a more efficient method? Specifically, I'm wondering if there a regex method to get an integer from a string, since \d already recognizes it as a number, right?

Thanks for any help.

After few proofs I found this way:

>>> s = '34, 58'
>>> print ( tuple( int(i) for i in s.split(', ') ) )
(34, 58)
Member Avatar for cyon

Thanks for your reply. I guess I should have clarified that it is important that the string should match the regex pattern to allow more flexibility for the user's input. But thanks for your solution, I will definitely be able to use that elsewhere...

I do not understand your input as you know already the number pair, but seem to like to return it anyway.

use re.split

>>> import re
>>> s = "84, 21"
>>> li = re.split("\D+", s)
>>> li
['84', '21']
>>> for i in range(len(li)):
...     li[i] = int(li[i])
>>> li
[84, 21]
>>> tu = tuple(li)
>>> tu
(84, 21)
commented: Thanks, ultimatebuster, that's what I was looking for! +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.