简体   繁体   English

如何在Python中检查字符串中是否包含某些相同的字符?

[英]How can i check if a string has some of the same characters in it in Python?

In my program, when a user inputs a word, it needs to be checked for letters that are the same. 在我的程序中,当用户输入单词时,需要检查单词是否相同。

For example, in string = "hello" , hello has 2 'l's. 例如,在string = "hello" ,hello具有2'l。 How can i check for this in a python program? 我如何在python程序中检查此内容?

Use a Counter object to count characters, returning those that have counts over 1. 使用Counter对象对字符进行计数,返回计数超过1的字符。

from collections import Counter

def get_duplicates(string):
    c = Counter(string)
    return [(k, v) for k, v in c.items() if v > 1]

In [482]: get_duplicates('hello')
Out[482]: [('l', 2)]

In [483]: get_duplicates('helloooo')
Out[483]: [('l', 2), ('o', 4)]

You can accomplish this with 您可以使用

d = defaultdict(int)

def get_dupl(some_string):
    # iterate over characters is some_string
    for item in some_string:
        d[item] += 1
    # select all characters with count > 1
    return dict(filter(lambda x: x[1]>1, d.items()))

print(get_dupl('hellooooo'))

which yields 产生

{'l': 2, 'o': 5}

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

相关问题 "<i>How can I check if a string has the same characters?<\/i>如何检查字符串是否具有相同的字符?<\/b> <i>Python<\/i> Python<\/b>" - How can I check if a string has the same characters? Python 我如何用正则表达式检查字符串,该字符串包含12个字符并包含0-9a-f? - How I can check a string with Regular expressions about the string has 12 characters and contains 0-9a-f? 如何有效地检查字符串在 C++ 中是否包含特殊字符? - How can I check if a string has special characters in C++ effectively? 检查字符串在python中是否只有白色字符 - check if a string has only white characters in python 如何将字符与Python中某个字符串中的所有字符进行比较? - How do I compare a character to all the characters in some string in Python? 如何在C ++中将某些字符复制到字符串中 - how can I copy some characters into string in c++ 如何获得字符串中另一个字符周围的一些字符? - How can I get some characters around another character in a string? 如何检查字符串是否仅包含拉丁字符? - How can I check if a string contains only latin characters? 如何检查字符串中的字符,数字和特殊字符? - How can i check for character , number and special characters in a string? 如何检查字符串是否包含字符和空格,而不仅仅是空格? - How can I check if string contains characters & whitespace, not just whitespace?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM