AP2*_*257 40 python regex string
我怀疑这是一个正则表达式问题 - 而且是一个非常基本的问题,所以道歉.
在Python中,如果我有一个类似的字符串
"xdtwkeltjwlkejt7wthwk89lk"
Run Code Online (Sandbox Code Playgroud)
如何获取字符串中第一个数字的索引?
谢谢!
bgp*_*ter 65
用途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
Run Code Online (Sandbox Code Playgroud)
Anu*_*yal 17
这是一种更好,更灵活的方式,正则表达式在这里有点过分.
s = 'xdtwkeltjwlkejt7wthwk89lk'
for i, c in enumerate(s):
if c.isdigit():
print(i)
break
Run Code Online (Sandbox Code Playgroud)
输出:
15
Run Code Online (Sandbox Code Playgroud)
要获得所有数字及其位置,可以使用简单的表达式
>>> [(i, c) for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()]
[(15, '7'), (21, '8'), (22, '9')]
Run Code Online (Sandbox Code Playgroud)
在Python 2.7+中,您可以创建数字及其位置的字典
>>> {c: i for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()}
{'9': 22, '8': 21, '7': 15}
Run Code Online (Sandbox Code Playgroud)
Pau*_*ine 11
对于解析器来说似乎是一个好工作:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
import re
first_digit = re.search('\d', 'xdtwkeltjwlkejt7wthwk89lk')
if first_digit is not None:
print(first_digit.start())
Run Code Online (Sandbox Code Playgroud)
以为我会把我的方法扔到一堆.我会做任何事来避免正则表达式.
sequence = 'xdtwkeltjwlkejt7wthwk89lk'
i = [x.isdigit() for x in sequence].index(True)
Run Code Online (Sandbox Code Playgroud)
要解释这里发生了什么:
[x.isdigit() for x in sequence] 将字符串转换为一个布尔数组,表示每个字符是否为数字[...].index(True)返回找到的第一个索引值True.要获取所有索引,请执行以下操作:
idxs = [i for i in range(0, len(string)) if string[i].isdigit()]
Run Code Online (Sandbox Code Playgroud)
然后要获得第一个索引,请执行以下操作:
if len(idxs):
print(idxs[0])
else:
print('No digits exist')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61827 次 |
| 最近记录: |