Python 查找字符串中第一个数字的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4510709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find the index of the first digit in a string
提问by AP257
I have a string like
我有一个像
"xdtwkeltjwlkejt7wthwk89lk"
how can I get the index of the first digit in the string?
如何获取字符串中第一个数字的索引?
采纳答案by bgporter
Use re.search():
使用re.search():
>>> import re
>>> s1 = "thishasadigit4here"
>>> m = re.search(r"\d", s1)
>>> if m is not None:
... print("Digit found at position", m.start())
... else:
... print("No digit in that string")
...
Digit found at position 13
回答by moinudin
As the other solutions say, to find the index of the first digit in the string we can use regular expressions:
正如其他解决方案所说,要找到字符串中第一个数字的索引,我们可以使用正则表达式:
>>> s = 'xdtwkeltjwlkejt7wthwk89lk'
>>> match = re.search(r'\d', s)
>>> print match.start() if match else 'No digits found'
15
>>> s[15] # To show correctness
'7'
While simple, a regular expression match is going to be overkill for super-long strings. A more efficient way is to iterate through the string like this:
虽然很简单,但对于超长字符串来说,正则表达式匹配将是过度的。更有效的方法是像这样遍历字符串:
>>> for i, c in enumerate(s):
... if c.isdigit():
... print i
... break
...
15
In case we wanted to extend the question to finding the first integer(not digit) and what it was:
如果我们想将问题扩展到查找第一个整数(不是数字)及其内容:
>>> s = 'xdtwkeltjwlkejt711wthwk89lk'
>>> for i, c in enumerate(s):
... if c.isdigit():
... start = i
... while i < len(s) and s[i].isdigit():
... i += 1
... print 'Integer %d found at position %d' % (int(s[start:i]), start)
... break
...
Integer 711 found at position 15
回答by Massimiliano Torromeo
I'm sure there are multiple solutions, but using regular expressions you can do this:
我确定有多种解决方案,但使用正则表达式可以做到这一点:
>>> import re
>>> match = re.search("\d", "xdtwkeltjwlkejt7wthwk89lk")
>>> match.start(0)
15
回答by drhanlau
you can use regular expression
你可以使用正则表达式
import re
y = "xdtwkeltjwlkejt7wthwk89lk"
s = re.search("\d",y).start()
回答by Christian
import re
first_digit = re.search('\d', 'xdtwkeltjwlkejt7wthwk89lk')
if first_digit is not None:
print(first_digit.start())
回答by Anurag Uniyal
Here is a better and more flexible way, regex is overkill here.
这是一种更好、更灵活的方法,正则表达式在这里有点过分。
s = 'xdtwkeltjwlkejt7wthwk89lk'
for i, c in enumerate(s):
if c.isdigit():
print(i)
break
output:
输出:
15
To get all digits and their positions, a simple expression will do
要获得所有数字及其位置,一个简单的表达式就可以了
>>> [(i, c) for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()]
[(15, '7'), (21, '8'), (22, '9')]
Or you can create a dict of digit and its last position
或者您可以创建一个数字及其最后位置的字典
>>> {c: i for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()}
{'9': 22, '8': 21, '7': 15}
回答by Paulo Scardine
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]
回答by kindall
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).
这是另一种无正则表达式的方式,更多的是功能风格。此方法查找字符串中存在的每个数字第一次出现的位置,然后选择最低的。正则表达式可能会更有效,尤其是对于较长的字符串(这使得至少 10 次完整通过字符串,最多 20 次)。
haystack = "xdtwkeltjwlkejt7wthwk89lk"
digits = "012345689"
found = [haystack.index(dig) for dig in digits if dig in haystack]
firstdig = min(found) if found else None
回答by alukach
Thought I'd toss my method on the pile. I'll do just about anything to avoid regex.
以为我会把我的方法扔在一堆。我会做任何事情来避免正则表达式。
sequence = 'xdtwkeltjwlkejt7wthwk89lk'
i = [x.isdigit() for x in sequence].index(True)
To explain what's going on here:
为了解释这里发生了什么:
[x.isdigit() for x in sequence]is going to translate the string into an array of booleans representing whether each character is a digit or not[...].index(True)returns the first index value thatTrueis found in.
[x.isdigit() for x in sequence]将字符串转换为布尔数组,表示每个字符是否为数字[...].index(True)返回在其中True找到的第一个索引值。
回答by michael toback
import re
result = " Total files:................... 90"
match = re.match(r".*[^\d](\d+)$", result)
if match is not None:
print(match.group(1))
will output
会输出
90

