简体   繁体   中英

How do I compare a character to all the characters in some string in Python?

I need to write a function that takes a character and a string as inputs and then compares that character to each element in the string. It then prints and finally returns the number of times that the character appeared in the string.

This is the code I've come up with, but it isn't working out the right way. I'd appreciate it if someone could explain and correct the error.

I thought first to write a function that compares two characters to check if they are equal, like this:

def func1(x1, x2):
    if x1 == x2:
        return True
    else:
        return False

And then, I thought I'd wite the other, main function like this:

def func2():
    ch1 = input("Enter one character. ")
    str1 = str(input("Enter a string. "))
    list_1 = list(str1)
    a = 0
    for 1 in list_1:
        if func1(ch1, list_1):
            a += 1
        else:
            a += 0
        print(a)
        return a

What is the error here? If I choose "a" as my character, and then enter a string of five a's as my string, the function still tells me that "a" appeared in the string only once. Why is this and how do I fix it?

"YourString".count("Char")

To fix your immediate problem, you just need to dedent the print and return

def func2():
    ch1 = input("Enter one character. ")
    str1 = str(input("Enter a string. "))
    list_1 = list(str1)
    a = 0
    for 1 in list_1:
        if func1(ch1, list_1):
            a += 1
        else:
            a += 0
    print(a)  # <-- dedent
    return a  # <-- dedent

You don't need to convert the string to a list to iterate over it. You don't need the else clause if it doesn't do anything. You shouldn't return from inside the for loop

def func2():
    ch1 = input("Enter one character. ")
    str1 = input("Enter a string. ")
    a = 0
    for c in str1:
        if c == ch:
            a += 1
        print(a)
    return a

More simply

def func2():
    ch1 = input("Enter one character. ")
    str1 = input("Enter a string. ")
    return str1.count(ch1)

Here is a simple code that does what you want:

It returns the number of times the character ch appears in text.

def test(ch, text): // ch is character and text is the string
    numAppears = 0
    for t in text:
        if t == ch:
            numAppears += 1
    return numAppears

example:

>>> test("a", "saherbaderahwal")
4
>>> test("c", "hello")
0
>>> test(" ", "nice to meet you")
3
>>> 

Few possible ways.

Using list

>>> len([x for x in test_string if x == test_char])

Using collections.Counter

>>> from collections import Counter
>>> print(Counter(test_string)[test_char])

The problem is that the return is indented one block to deep, so after comparing the first character of the list, the function returns.

(Another problem is that your function func1 is not only poorly named, but also far too complicated:

def cmp_chars(x, y):
    return x == y

Though you really don't need a function for that at all.)

假设您放置在其中的代码格式正确,则不会使您的return代码缩进一格-好像它在for块中被调用了一次

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM