Check if both halves of the string have same set of characters in Python

We can split a long string from the middle and check if the two halves are equal or not. The input string may have an odd or even number of characters. If it has an even number of characters, we divide the two halves by taking half of the length. But if the number of characters is odd then we ignore the middlemost character and then compare the remaining two halves.

In the below program we create the two halves of the input string with above logic and then


from collections import Counter
def comparehalves(input_string):
   str_len = len(input_string)
# If number of characyes is odd
# ignore the middle character
   if (str_len % 2 != 0):
      left = input_string[0:int(str_len / 2)]
      right = input_string[(int(str_len / 2)) + 1:]
      left = input_string[0:int(str_len / 2)]
      right = input_string[int(str_len / 2):]
# Convert the halves into lists
# and sort them
   l1 = list(left)
   l2 = list(right)
   if l1 == l2:
      print ("Same character in both halves")
      print ("Both halves are different ")
in_string = input("Enter String: ")


Running the above code gives us the following result −

# Run1
Enter String: Tutorials
Both halves are different
# Run2
Enter String: TutTut
Same character in both halves

Updated on: 17-Oct-2019


Kickstart Your Career

Get certified by completing the course

Get Started