Python – Check if Splits are equal


When it is required to check if the splits in a string are equal, the ‘len’ method, ‘list’ method and the ‘set’ operator are used along with an ‘if’ condition.

Example

Below is a demonstration of the same −

my_string = '96%96%96%96%96%96'

print("The string is : " )
print(my_string)

my_split_char = "%"
print("The character on which the string should be split is :")
print(my_split_char)

my_result = len(list(set(my_string.split(my_split_char)))) == 1

print("The resultant list is : ")

if(my_result == True):
   print("All the splits are equal")
else:
   print("All the splits are not equal")

Output

The string is :
96%96%96%96%96%96
The character on which the string should be split is :
%
The resultant list is :
All the splits are equal

Explanation

  • A string is defined and is displayed on the console.

  • The character based on which the string should be split is defined.

  • It is also displayed on the console.

  • The string is split based on this character, and is converted to a set, to get the unique elements.

  • This is converted to a list.

  • Its length is checked to be equivalent to 1.

  • If yes, this Boolean value is stored in a variable.

  • Based on the value of this Boolean variable, a relevant message is displayed on the console.

Updated on: 13-Sep-2021

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements