首页 > 解决方案 > 计算字符串中特殊字符的出现次数(仅限 while 和 for 循环,无函数)

问题描述

我的程序必须仅使用 while 或 for 循环(不允许使用内置函数)来计算字符串中有多少特殊字符。

def compteMembres(s):

    special_chars = 'F' or '4' or 
    i = 0
    while i < len(s):
        q = 0
        if special_chars in s:
            q = q + 1                 
        i = i + 1       
    return q

s = input("Enter string: ")

compteMembres(s)

标签: pythonstringfor-loopwhile-loopcount

解决方案


据我了解,当您指的是特殊字符时,您指的是不是数字或字母的字符。我更新了您的代码以查找字符串中特殊字符的数量:

def compteMembres(s):
    count = 0
    for i in range(len(s)):
        if not ('a' <= s[i] <= 'z' or 'A' <= s[i] <= 'Z' or '0' <= s[i] <= '9'):
            count += 1
    return count


s = input("Enter string: ")
print(compteMembres(s)) 

我希望这是您搜索的答案。如果你的意思是别的,请告诉我。


推荐阅读