check for repeated characters/letter in a string

前端 未结 3 1985
感情败类
感情败类 2021-01-29 07:12

hi i want to check if a string from user input has two repeated characters/letters in a string next to eachother.. i have a simple code to check if the first letter and second l

相关标签:
3条回答
  • 2021-01-29 07:20

    Another method that works is to use the repeating character syntax to check if a string contains the same character. Here is a snippet from a PyUnit test that illustrates doing this with several different strings which all contain some number of commas.

        # 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")
    
    0 讨论(0)
  • 2021-01-29 07:23

    As the comments already mentioned you should use a for loop:

    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 讨论(0)
  • 2021-01-29 07:30

    You can use set's feature of unique elements: if len(string_to_check) == len(set([char for char in string_to_check]))

    This way all repeated characters will be counted as one (for each type of character) in the set. Comparing length of string and set, it is possible fo get number of repeated characters

    0 讨论(0)
提交回复
热议问题