检查字符串中重复的字符/字母

时间:2015-12-10 22:28:39

标签: python character

嗨我想检查来自用户输入的字符串是否在彼此旁边的字符串中有两个重复的字符/字母..我有一个简单的代码来检查字符串中的第一个字母和第二个字母是否相同。< / p>

def two_same():
    d = []
    while len(d) <= 1:
        d = input("enter the same letter twice:")
    if d[0] == d[1]:
        return print(d[0])
two_same()

但我如何检查字符串中的所有字符以及用户输入的重复字母。

3 个答案:

答案 0 :(得分:1)

正如已经提到的评论,你应该使用for循环:

def two_same(string)
   for i in range(len(string)-1):
      if string[i] == string[i+1]:
         return True
   return False

result = ""
while not two_same(result):
   result = input("enter the same letter twice:")
print(result)

答案 1 :(得分:0)

另一种有效的方法是使用重复字符语法来检查字符串是否包含相同的字符。下面是PyUnit测试的一个片段,它说明了使用几个不同的字符串来执行此操作,这些字符串都包含一些逗号。

    # simple test
    test_string = ","

    self.assertTrue(test_string.strip() == "," * len(test_string.strip()),
                    "Simple test failed")

    # Slightly more complex test by adding spaces before and after
    test_string = " ,,,,, "

    self.assertTrue(test_string.strip() == "," * len(test_string.strip()),
                    "Slightly more complex test failed")

    # Add a different character other than the character we're checking for
    test_string = " ,,,,,,,,,a "

    self.assertFalse(test_string.strip() == "," * len(test_string.strip()),
                     "Test failed, expected comparison to be false")

    # Add a space in the middle
    test_string = " ,,,,, ,,,, "

    self.assertFalse(test_string.strip() == "," * len(test_string.strip()),
                     "Test failed, expected embedded spaces comparison to be false")

    # To address embedded spaces, we could fix the test_string 
    # and remove all spaces and then run the comparison again
    fixed_test_string = "".join(test_string.split())
    print("Fixed string contents: {}".format(fixed_test_string))
    self.assertTrue(fixed_test_string.strip() == "," * len(fixed_test_string.strip()),
                    "Test failed, expected fixed_test_string comparison to be True")

答案 2 :(得分:0)

您可以使用set的独特元素功能: if len(string_to_check)== len(set([char_class_to_check中的char为char])

这样,所有重复的字符将被计为一组(对于每种类型的字符)。比较字符串和集合的长度,可以获得重复字符的数量