簡體   English   中英

如何計算python字符串中的整數數量

[英]How to calculate the number of integers in a python string

我想計算字符串"abajaao1grg100rgegege"的整數數。 我嘗試使用isnumeric()但是它將'100'視為三個不同的整數,並顯示輸出4。我希望我的程序將100視為一個整數。

這是我的嘗試:

T = int(input()) 
for x in range(T): 
    S = input() 
    m = 0 
    for k in S: 
        if (k.isnumeric()): 
            m += 1 
print(m)

我會使用非常基本的正則表達式(\\d+)然后計算匹配項的數量:

import re

string = 'abajaao1grg100rgegege'
print(len(re.findall(r'(\d+)', string)))
# 2

正如其他答案所指出的那樣,正則表達式是解決此類問題的首選工具。 但是,以下是使用循環構造而不使用正則表達式的解決方案:

result = sum(y.isdigit() and not x.isdigit() for x,y in zip(myString[1:], myString))

另外,這是一個易於理解的迭代解決方案,它也沒有使用正則表達式,比另一個更清晰,但也更冗長:

def getNumbers(string):
    result = 0
    for i in range(len(string)):
        if string[i].isdigit() and (i==0 or not string[i-1].isdigit()):
            result += 1
    return result

您可以使用正則表達式庫來解決此問題。

import re
st = "abajaao1grg100rgegege"
res = re.findall(r'\d+', st)

>>> ['1', '100']

您可以檢查findall返回的那個列表上有多少個數字。

print (len(res))
>>> 2

為了閱讀有關python正則表達式和模式的更多信息,請在此處輸入

不是非常Pythonic,但對於初學者來說更容易理解:

循環遍歷string中的字符,並且在每次迭代中,如果當前字符為digit,請記住was_digit (邏輯變量) -用於一次迭代。

僅當前一個字符不是數字時才增加計數器:

string = 'abajaao1grg100rgegege'
counter = 0                   # Reset the counter
was_digit = False             # Was previous character a digit?

for ch in string:
    if ch.isdigit():
        if not was_digit:     # previous character was not a digit ...
            counter += 1      # ... so it is start of the new number - count it!
        was_digit = True      # for the next iteration
    else:
        was_digit = False     # for the next iteration

print(counter)                # Will print 2
random="1qq11q1qq121a21ws1ssq1";
counter=0
i=0
length=len(random)
while(i<length):
  if (random[i].isnumeric()):
    z=i+1
    counter+=1
    while(z<length):
      if (random[z].isnumeric()):
        z=z+1
        continue
      else:
        break
    i=z
  else:
    i+=1
print ("No of integers",counter)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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