I have a string like
\"xdtwkeltjwlkejt7wthwk89lk\"
how can I get the index of the first digit in the string?
In Python 3.8+ you can use re.search to look for the first \d
(for digit) character class like this:
import re
my_string = "xdtwkeltjwlkejt7wthwk89lk"
if first_digit := re.search(r"\d", my_string):
print(first_digit.start())
instr = 'nkfnkjbvhbef0njhb h2konoon8ll'
numidx = next((i for i, s in enumerate(instr) if s.isdigit()), None)
print numidx
output:
12
numidx will be the index of the first occurrence of a digit in instr. If there are no digits in instr, numidx will be None.
I didn't see this solution here, and thought it should be.
import re
first_digit = re.search('\d', 'xdtwkeltjwlkejt7wthwk89lk')
if first_digit:
print(first_digit.start())
Here is another regex-less way, more in a functional style. This one finds the position of the first occurrence of each digit that exists in the string, then chooses the lowest. A regex is probably going to be more efficient, especially for longer strings (this makes at least 10 full passes through the string and up to 20).
haystack = "xdtwkeltjwlkejt7wthwk89lk"
digits = "012345689"
found = [haystack.index(dig) for dig in digits if dig in haystack]
firstdig = min(found) if found else None
import re
result = " Total files:................... 90"
match = re.match(r".*[^\d](\d+)$", result)
if match:
print(match.group(1))
will output
90
Seems like a good job for a parser:
>>> from simpleparse.parser import Parser
>>> s = 'xdtwkeltjwlkejt7wthwk89lk'
>>> grammar = """
... integer := [0-9]+
... <alpha> := -integer+
... all := (integer/alpha)+
... """
>>> parser = Parser(grammar, 'all')
>>> parser.parse(s)
(1, [('integer', 15, 16, None), ('integer', 21, 23, None)], 25)
>>> [ int(s[x[1]:x[2]]) for x in parser.parse(s)[1] ]
[7, 89]