check for repeated characters/letter in a string

拜拜、爱过 提交于 2019-12-20 07:49:30

问题


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 letter in the string are the same.

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

but how would i check all the characters in the string and for a repeated letter from a user input.


回答1:


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)



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/34212898/check-for-repeated-characters-letter-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!