【问题标题】:Count the number occurrences of a special character in a string (while and for loops only, no functions)计算字符串中特殊字符的出现次数(仅限 while 和 for 循环,无函数)
【发布时间】:2021-03-13 01:04:46
【问题描述】:

我的程序必须仅使用 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)

【问题讨论】:

  • 嘿。你能更具体一点,当你说特殊字符时你的意思是什么?不是数字或字母?

标签: python string for-loop while-loop count


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 1970-01-01
    • 2021-08-22
    • 2019-04-05
    • 2011-07-08
    • 2019-10-08
    • 2018-11-05
    • 2014-04-24
    相关资源
    最近更新 更多