[英]How to get the total number of digits at the end of the string
I have a list containing server names like ['oracle0123','oracle0124','oracle0125']
.我有一个包含服务器名称的列表,例如
['oracle0123','oracle0124','oracle0125']
。 I want to check how many digits are at the end of the server name, as this varies (as in this case, it is 4).我想检查服务器名称末尾有多少位数,因为这会有所不同(在本例中为 4)。 I have a vague idea how this should be done, but my approach didn't work.
我有一个模糊的想法应该如何做到这一点,但我的方法没有奏效。
v=['oracle0123','oracle0124','oracle0125']
def get_num_position(v):
for i in v:
i=i[::-1]
print('reverse server is-',i)
for j in i:
x=0
if j.isdigit():
x = x+1
print(x)
return x
get_num_position(v)
You could also use re.split
to achieve this:您也可以使用
re.split
来实现这一点:
>>> import re
>>> s = "oracle1234ad123"
>>> first, _ = re.split("\d+$", s)
>>> len(s) - len(first)
3
Note that the code above will fail, if the input string does not end with the number:请注意,如果输入字符串不以数字结尾,则上面的代码将失败:
>>> first, _ = re.split("\d+$", "foobar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 2, got 1)
In Python 3 you could use the *
assignment, to avoid such errors:在 Python 3 中,您可以使用
*
赋值,以避免此类错误:
>>> first, *rest = re.split("\d+$", "foobar")
>>> first
'foobar'
>>> rest
[]
The problem is that you're resetting the value of x
to 0 for every character.问题是您将每个字符的
x
值重置为 0。 Also, I'm guessing you wanted to print x
only after looping through each word.另外,我猜您只想在遍历每个单词后才打印
x
。 This should work without changing the logic of your code much:这应该在不改变代码逻辑的情况下工作:
v=['oracle0123','oracle0124','oracle0125']
def get_num_position(v):
for i in v:
i=i[::-1]
print('reverse server is-',i)
x=0
for j in i:
if j.isdigit():
x = x+1
print(x)
get_num_position(v)
This would work fine for you.这对你来说很好。
code
代码
v=['oracle0123','oracle0124','oracle0125']
def get_num_position(v):
count = []
for i in v:
tCount = 0
for j in i:
if j.isnumeric():
tCount += 1
print(tCount)
count.append(tCount)
return count
get_num_position(v)
Output:
Output:
4
4
4
Try:尝试:
import re
for i in v:
match=re.search(r'\d+$',i)
if match:
print(i, len(match.group()))
else:
print(i, '0')
r'\d*$'
$
from the end $
从最后\d*
find all the digits \d*
查找所有数字re.search
finds the pattern re.search
找到模式.group
returns the match group .group
返回匹配组len
determines the length of the group len
确定组的长度len
of numbers at the endlen
import re
values = ['oracle01234',
'oracle012468',
'oracle01258575',
'0123oracle0123',
'0123oracle0124555',
'0123oracle01255',
'ora0123cle01234',
'or0123acle0124333333',
'o0123racle01254',
'123or0123acle0124333333']
count_of_end_numbers = [len(re.search(r'\d*$', x).group()) for x in values]
print(count_of_end_numbers)
>>> [5, 6, 8, 4, 7, 5, 5, 10, 5, 10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.