Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the first character and integer pair in a Python string?

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?

like image 484
ShanZhengYang Avatar asked Mar 07 '26 12:03

ShanZhengYang


1 Answers

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)
like image 120
Kevin Fang Avatar answered Mar 09 '26 02:03

Kevin Fang



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!