-1

I want to pick up a substring from <personne01166+30-90>, which the output should look like: +30 and -90.

The strings can be like: 'personne01144+0-30', 'personne01146+0+0', 'personne01180+60-75', etc.

I tried use

<string.split('+')[len(string.split('+')) -1 ].split('+')[0]>

but the output must be two correspondent numbers.

Red
  • 26,798
  • 7
  • 36
  • 58
  • It looks like you are looking to create a regex, but do not know where to get started. Please check [Reference - What does this regex mean](https://stackoverflow.com/questions/22937618) resource, it has plenty of hints. Also, refer to [Learning Regular Expressions](https://stackoverflow.com/questions/4736) post for some basic regex info. Once you get some expression ready and still have issues with the solution, please edit the question with the latest details and we'll be glad to help you fix the problem. – Wiktor Stribiżew Nov 23 '20 at 13:11

2 Answers2

0

Here is how you can use a list comprehension and re.findall:

import re

s = ['personne01144+0-30', 'personne01146+0+0', 'personne01180+60-75']

print([re.findall('[+-]\d+', i) for i in s])

Output:

[['+0', '-30'], ['+0', '+0'], ['+60', '-75']]

re.findall('[+-]\d+', i) finds all the patterns of '[+-]\d+' in the string i.

[+-] means any either + or -. \d+ means all numbers in a row.

Red
  • 26,798
  • 7
  • 36
  • 58
0

If you know the interesting part always comes after + then you can simply split twice.

numbers = string.split('+', 1)[1]
if '+' in numbers:
    this, that = numbers.split('+')
elif '-' in numbers:
    this, that = numbers.split('-')
    that = -that
else:
    raise ValueError('Could not parse %s', string)

Perhaps a regex-based approach makes more sense, though;

import re
m = re.search(r'([-+]\d+)([-+]\d+)$', string)
if m:
    this, that = m.groups()
tripleee
  • 175,061
  • 34
  • 275
  • 318