Check if All Characters Same

Check if all characters in string are same.

IntermediatePhase 5 - Category 5: Advanced String LogicExample 6 of 14
check-if-all-characters-same.py
1# Take string input
2s = input("Enter a string: ")
3
4# Check if all same
5if len(s) == 0:
6 print("Empty string")
7elif len(set(s)) == 1:
8 print("All characters are same")
9else:
10 print("Characters are different")

Output

Enter a string: aaaa
All characters are same

Enter a string: hello
Characters are different

What's going on

Use set to check unique characters.

Key Concepts:

set(s) gives unique characters
If length is 1, all same
Otherwise, different