Python – Check if Splits are equal

When you need to check if all parts of a split string are equal, you can use the set() function along with split(). This approach converts the split result to a set to get unique elements, then checks if only one unique element exists.

Example

Below is a demonstration of checking if splits are equal ?

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(set(my_string.split(my_split_char))) == 1

print("The resultant check is :")

if my_result:
    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 check is :
All the splits are equal

How It Works

The algorithm works by following these steps ?

  • Split the string using the specified delimiter character

  • Convert the split result to a set to get only unique elements

  • Check if the length of the set equals 1 (meaning all splits were identical)

  • Return True if all splits are equal, False otherwise

Example with Different Splits

Here's an example where splits are not equal ?

my_string = 'apple,banana,apple,orange'
my_split_char = ","

splits = my_string.split(my_split_char)
print("Split result:", splits)

are_equal = len(set(splits)) == 1
print("All splits equal:", are_equal)
Split result: ['apple', 'banana', 'apple', 'orange']
All splits equal: False

Alternative Approach

You can also use the all() function for a more readable solution ?

def check_splits_equal(string, delimiter):
    splits = string.split(delimiter)
    return all(part == splits[0] for part in splits)

# Test with equal splits
result1 = check_splits_equal('96%96%96%96', '%')
print("Equal splits:", result1)

# Test with different splits
result2 = check_splits_equal('a,b,c', ',')
print("Different splits:", result2)
Equal splits: True
Different splits: False

Conclusion

Use len(set(string.split(delimiter))) == 1 to check if all splits are equal. The set approach is efficient as it automatically handles duplicate checking. For better readability, consider using the all() function approach.

Updated on: 2026-03-26T01:44:22+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements