user2697881
user2697881

Reputation: 93

Splitting string in Python starting from the first numeric character

I need to manage string in Python in this way:

I have this kind of strings with '>=', '=', '<=', '<', '>' in front of them, for example:

'>=1_2_3'
'<2_3_2'

what I want to achieve is splitting the strings to obtain, respectively:

'>=', '1_2_3' 
'<', '2_3_2'

basically I need to split them starting from the first numeric character.

There's a way to achieve this result with regular expressions without iterating over the string checking if a character is a number or a '_'?

thank you.

Upvotes: 1

Views: 3735

Answers (4)

heemayl
heemayl

Reputation: 41987

This will do:

re.split(r'(^[^\d]+)', string)[1:]

Example:

>>> re.split(r'(^[^\d]+)', '>=1_2_3')[1:]
['>=', '1_2_3']

>>> re.split(r'(^[^\d]+)', '<2_3_2')[1:]
['<', '2_3_2']

Upvotes: 3

Malik Brahimi
Malik Brahimi

Reputation: 16711

There's probably a better way but you can split with a capture then join the second two elements:

values = re.split(r'(\d)', '>=1_2_3', maxsplit = 1)
values = [values[0], values[1] + values[2]]

Upvotes: 0

jedwards
jedwards

Reputation: 30210

import re

strings = ['>=1_2_3','<2_3_2']

for s in strings:
    mat = re.match(r'([^\d]*)(\d.*)', s)
    print mat.groups()

Outputs:

('>=', '1_2_3')
('<', '2_3_2')

This just groups everything up until the first digit in one group, then that first digit and everything after into a second.

You can access the individual groups with mat.group(1), mat.group(2)

Upvotes: 2

anubhava
anubhava

Reputation: 784998

You can split using this regex:

(?<=[<>=])(?=\d)

RegEx Demo

Upvotes: 0

Related Questions