简体   繁体   English

如何将字符与Python中某个字符串中的所有字符进行比较?

[英]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. 如果我选择“ a”作为我的字符,然后输入一个由五个a组成的字符串作为我的字符串,该函数仍会告诉我“ a”在字符串中仅出现一次。 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. 如果它不执行任何操作,则不需要else子句。 You shouldn't return from inside the for loop 您不应该从for循环中返回

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. 它返回字符ch在文本中出现的次数。

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 使用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. 问题在于return值缩进了一个区块,因此比较该列表的第一个字符后,该函数返回。

(Another problem is that your function func1 is not only poorly named, but also far too complicated: (另一个问题是,函数func1不仅命名不正确,而且过于复杂:

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

Though you really don't need a function for that at all.) 虽然您实际上根本不需要任何功能。)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何替换 Python 字符串中的所有字符? - How do I replace all characters in a Python string? 如何通过匹配python中的某些字符从字符串中删除一些字符 - How to delete some characters from a string by matching certain character in python 如何获得字符串中另一个字符周围的一些字符? - How can I get some characters around another character in a string? 如何在python 3中的文本框数据上进行字符比较 - How do I do a character compare on text box data in python 3 我想在第一次出现时用一个字符分割一个字符串,该字符属于一个字符列表。 如何在python中做到这一点? - I want to split a string by a character on its first occurence, which belongs to a list of characters. How to do this in python? 如何在Python中比较字符串中的2行 - How do I compare 2 lines in a string in Python 如何对字符串中的所有字符(包括安全字符)进行 urlencode? - How do I urlencode all the characters in a string, including safe characters? 如何使用字符映射表替换字符串中的字符? - How do I replace characters in a string using a character map? 如何检查字符串是否包含字符和空格(空字符)? - How do I check if a string includes characters and space (empty character)? 如何在Python字符串中设置字符? - How do I set characters in a Python string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM