簡體   English   中英

如何獲取字符串末尾的總位數

[英]How to get the total number of digits at the end of the string

我有一個包含服務器名稱的列表,例如['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)

您也可以使用re.split來實現這一點:

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

在 Python 3 中,您可以使用*賦值,以避免此類錯誤:

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

這對你來說很好。

代碼

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

for i in v:
    match=re.search(r'\d+$',i)
    if match:
        print(i, len(match.group()))
    else:
        print(i, '0')

使用正則表達式:

  • r'\d*$'
    • $從最后
    • \d*查找所有數字
  • re.search找到模式
  • .group返回匹配組
  • len確定組的長度
  • 假設最后至少有一個數字
  • 使用列表理解
  • 示例已提供數字
    • 只在最后
    • 開始和結束
    • 中間和結尾
    • 開頭中間和結尾
  • 該代碼僅在末尾返回數字的len
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM