0

I am trying to parse out the final digits from a structure like so: "q1option4" -> 4. Another example: "q3option54 -> 54. I know there is probably an elegant way to do this in Python3, so I am looking for your help. Thanks!

  • If you know that the prefix will always be a `q`, followed by a single digit, followed by `option` - in other words, if the length of the prefix does not change - you can use simple string slicing to get all the characters starting at the 8th index, extending to the end: `"q3option54"[8:]` – Paul M. Apr 06 '21 at 11:48
  • 1
    If you'll always have `option` in the string, you can do something like `"q1option4".split('option')[-1]`. `.split` will split your string into pieces based on the splitting string. `[-1]` will give you the last element of the resulting list of strings. – JRajan Apr 06 '21 at 11:49
  • 1
    Does this answer your question? [How can I detect last digits in python string](https://stackoverflow.com/questions/13471976/how-can-i-detect-last-digits-in-python-string) – python_user Apr 06 '21 at 11:52

4 Answers4

1

You can use regular expressions for this:

import re

re.search(r"(\d+)$", "q1option54").group()

54

user1717828
  • 7,122
  • 8
  • 34
  • 59
0

If you know that all digits are at the end of the string, in one uninterrupted sequence, than search for first letter from the end of the string end slice the end of it.

seq = "q3option54"
seq_rev = seq[::-1] # reverse the sequence
rev_ind = 0

# find the last sequence of numbers
for ind, char in enumerate(seq_rev):
    if not char.isdigit():
        rev_ind = ind
        break

# slice off the digit part, and reverse it
digits = seq_rev[:rev_ind][::-1]
print(f'digits: {digits}')

output:

digits: 54

Antoni
  • 176
  • 10
0
import re

regex = re.compile(r'^(?:[a-zA-z]*\d*[a-zA-z]+)*(\d+)$')
examples = [
    "q1option4",
    "q3option54",
    "q3op23ti56on18",
    "q28",
    "11",
]

for e in examples:
    print(e, '-->', regex.match(e).groups()[0])

Outuput

q1option4 --> 4
q3option54 --> 54
q3op23ti56on18 --> 18
q28 --> 28
11 --> 11
PieCot
  • 3,564
  • 1
  • 12
  • 20
-1

One solution to this might be: s = your string

s = 'q1opstion4'
s[8:]
# returns 4

s = 'q1options54'
s[8:]
# returns 54

Aors
  • 89
  • 1
  • 4