check for repeated characters/letter in a string

前端 未结 3 1986
感情败类
感情败类 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")
    

提交回复
热议问题