如何获取字符串末尾的总位数

2024-10-02 08:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含服务器名的列表,比如['oracle0123','oracle0124','oracle0125']。我想检查服务器名称的末尾有多少个数字,因为这是不同的(在本例中,它是4)。我对如何做到这一点有一个模糊的想法,但我的方法不起作用。你知道吗

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)

Tags: in服务器名称列表forgetposition数字
3条回答

这对你很有用。你知道吗

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:

4
4
4

您还可以使用^{}来实现这一点:

>>> import re
>>> s = "oracle1234ad123"
>>> first, _ = re.split("\d+$", s)
>>> len(s) - len(first)
3

请注意,如果输入字符串未以数字结尾,则上述代码将失败:

>>> 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)

在Python3中,可以使用*赋值来避免此类错误:

>>> first, *rest = re.split("\d+$", "foobar")
>>> first
'foobar'
>>> rest
[]

问题是您正在为每个字符将x的值重置为0。而且,我猜您只想在循环遍历每个单词之后才打印x。这应该在不太改变代码逻辑的情况下工作:

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)

相关问题 更多 >

    热门问题