Python:如何使用while循环查找单个字符的出现?

时间:2015-11-27 16:08:32

标签: python python-3.x

def x(s, c):
    num = 0
    while (blank....here should enter some code):
        num = num + 1
    return num

在这个函数中,s表示一个字符串(即'banana'),c表示单个字符(即'a'),如果c在s中,则返回c的出现次数;如果c不在s中,则返回s的长度。 之后只有一行,那么我应该进入什么?

3 个答案:

答案 0 :(得分:0)

正如@poke已经提到的,你所需要的只是return s.count(c) or len(s)

def x(s, c):
    return s.count(c) or len(s)

def x(s, c):
    return s.lower().count(c.lower()) or len(s) 

答案 1 :(得分:0)

如果您不想使用任何预定义的字符串方法,您可以手动迭代字符串并计算所需字符的出现次数以及遇到的每个位置:

def x(s, c):
    occ = 0
    tot = 0
    it = iter(s)
    while True:
        try:
            if next(it) == c:
                occ += 1
        except StopIteration:
            return occ or tot
        finally:
            tot += 1

print(x('hello world','l'))
print(x('hello world','y'))

产生

3
11

答案 2 :(得分:0)

def x(s, c):
    num = 0
    for char in s: # Iterate through each character in the string
        if char == c: # If that character matches c
            num += 1 # Add 1 to num
    return num if num else len(s)