2015-12-10 46 views
-2

您好我想检查用户输入的字符串中是否有两个重复的字符/字母旁边的eachother ..我有一个简单的代码来检查是否第一个字母和第二个字符串中的字母是相同的。检查字符串中的重复字符/字母

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() 

但如何将我检查的字符串,并从用户输入重复字母的所有字符。

+1

使用'for'循环。 – Blender

+0

所有你需要做的就是跟踪最后一个字符并将其与当前循环进行比较,'return print(d [0])'也是无效的 –

回答

1

前面已经提到的意见,你应该使用一个循环:

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) 
+0

是的,但我需要用户输入,所以我需要重复用户输入,直到他们给我一个字符串有两个字符重复 – Sinoda

+0

编辑:我编辑了答案,以功能输入。 – Randrian

+0

但这个函数接受一个字符串作为参数,并且不要求用户输入 – Sinoda

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")