簡體   English   中英

如何檢查字符串中某個字符的多次出現

[英]How to check multiple occurrences of a character in a string

如果有一個字符串 = '99888',它應該打印 'True'。 如何檢查字符串中一個字符的對和三個字符

我嘗試使用計數 function 但它只識別一對

string = '99888'
for c in '123456789':
    if string.count(c) == 2 and string.count(c) == 3 :
       print('True')

編輯:該字符串始終是 5 個字符的字符串,如果有一對和三個,則打印 True 例如“89899”和“75757”打印 True。 '98726' 打印 False

  • 使用collections模塊中的Counter class
from collections import Counter

def check(inputString):
    x = Counter(inputString)
    list_of_counts = [x[i] for i in x.elements()]

    if (2 in list_of_counts) and (3 in list_of_counts):
        return(True)
    else:
        return(False)

print(check("99888"))
print(check("999888"))

暫無
暫無

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

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