Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in Python until one of specific characters occurs from right to left?

What is the best way to split a string into two parts in Python from right to left until one of several characters occur?

The aim is to separate a string into two parts with a version number (beginning with either A, B or C) at the end for examples like these:

  • EP3293036A1 -> EP3293036 + A1
  • US10661612B2 -> US10661612 + B2
  • CN107962948A -> CN107962948 + A
  • ES15258411C1 -> ES15258411 + C1

My code works for splitting the string for a single character:

first_part = number.rpartition('A')[0]
second_part = number.rpartition('A')[1] + number.rpartition('A')[2]

Is there a way to have multiple arguments like ('A' or 'B' or 'C') using rpartition? Or is there a better way using regex?

like image 665
screensaver Avatar asked Dec 28 '25 21:12

screensaver


1 Answers

Use re.findall. Using the regex shown, this function extracts the parts in parentheses: (.*?) - any characters repeated 0 or more times, non-greedy; ([AB]\d*)$ - A or B, followed by 0 or more digits, followed by the end of the string.

import re
lst = ['EP3293036A1', 'EP3293036B']

for s in lst:
    parts = re.findall(r'(.*?)([AB]\d*)$', s)
    print(f's={s}; parts={parts}')

# s=EP3293036A1; parts=[('EP3293036', 'A1')]
# s=EP3293036B; parts=[('EP3293036', 'B')]
like image 69
Timur Shtatland Avatar answered Dec 30 '25 10:12

Timur Shtatland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!