Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Check if All Characters Same

Check whether all string positions contain the same character. Students use Python set size while treating case, spaces, and empty input as distinct concerns.

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

In this one

  • Use a character set
  • Separate empty from all-same
  • Retain case distinctions

How it works

  1. 1

    Handle an empty response first.

  2. 2

    Calculate len(set(s)) for nonempty text.

  3. 3

    Accept exactly one distinct character.

Edge cases

Does one character pass?

Does one character pass?

Yes. The set has one member.

What about empty text?

What about empty text?

It prints Empty string.

What's going on

set(s) retains the distinct characters present. A size of one means all positions hold the same character.

The empty response has its own message rather than being declared all-same. A single character passes. Case and whitespace are significant: aaA has two distinct characters, while three ordinary spaces have one. No sorting or normalization is used.

Does one character pass? Yes. The set has one member.

What about empty text? It prints Empty string.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does aaA produce?

Pick an answer to check it.

Question 2

Does one character pass?

Pick an answer to check it.

Questions people ask

Does one character pass?

Yes. The set has one member.

What about empty text?

It prints Empty string.

What does aaA produce?

Characters are different.