3

I have several strings in Python. Let's assume each string is associated with a variable. These strings are only composed of characters and integers:

one = '74A76B217C'
two = '8B7A1742B'
three = '8123A9A8B'

I would like a conditional in my code which checks these strings if 'A' exists first, and if so, return the integer.

So, in the example above, the first integer and first character is: for one, 74 and A; for two, 8 and B; for three, 8123 and A.

For the function, one would return True, and 74; two would be False, and three would be 8123 and A.

My problem is, I am not sure how to efficiently parse the strings in order to check for the first integer and character.

In Python, there are methods to check whether the character exists in the string, e.g.

if 'A' in one:
    print('contains A')

But this doesn't take order into account order. What is the most efficient way to access the first character and first integer, or at least check whether the first character to occur in a string is of a certain identity?

2
  • What should happen for five = 'A123BCD' and six = 'A1A2A3' Commented Dec 4, 2018 at 1:22
  • @mtrw The integers always come first. Commented Dec 4, 2018 at 13:51

4 Answers 4

3

Try this as an alternative of regex:

def check(s):
    i = s.find('A')
    if i > 0 and s[:i].isdigit():
        return int(s[:i]), True
    return False

# check(one) (74, True)
# check(two) False
# check(three) (8123, True)
Sign up to request clarification or add additional context in comments.

Comments

2

Use regex: ^(\d+)A

import re

def check_string(s):
    m_test = re.search("^(\d+)A", s)
    if m_test:
        return m_test.group(1)

See online regex tester: https://regex101.com/r/LmSbly/1

Comments

1

Try a regular expression.

>>> import re
>>> re.search('[0-9]+', '74A76B217C').group(0)
'74'
>>> re.search('[A-z]', '74A76B217C').group(0)
'A'

Comments

1

You can use a regex:

>>> re.match('^([0-9]+)A', string)

For example:

import re

for s in ['74A76B217C', '8B7A1742B', '8123A9A8B']:
    match = re.match('^([0-9]+)A', s)
    print(match is not None and match.group(1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.