How to Compare Strings in Python

What you’ll build or solve

You’ll compare Python strings for equality and ordering, with results you can trust. .

When this approach works best

Comparing strings works well when you:

  • Validate user input, like checking a command ("yes", "no") or a username.
  • Filter or search, like finding matching tags or detecting duplicates.
  • Apply ordering checks, like validating that a value falls between "a" and "m".

Skip direct comparisons when you need language-aware sorting (locale rules) or fuzzy matching (typos). In those cases, use a dedicated collation or similarity tool.

Prerequisites

  • Python 3 installed
  • You know what a string is

Step-by-step instructions

1) Compare for equality with ==

Use == to check if two strings contain the same characters in the same order.

a="hello"
b="hello"

print(a==b)

What to look for: == checks content, not whether the variables point to the same object.


2) Normalize strings before comparing

User input often varies in casing and whitespace. Clean it first, then compare.

Option A: ignore leading/trailing whitespace with .strip()

Option B: compare case-insensitively with .casefold() (stronger than .lower())

raw="  YES\n"
expected="yes"

clean=raw.strip().casefold()
print(clean==expected)

What to look for: .casefold() handles more Unicode case rules than .lower(), which helps with non-English text.


3) Compare for ordering with < and >

Use ordering comparisons for alphabetical checks or range validation.

print("apple"<"banana")# True
print("Z"<"a")# True

What to look for: ordering uses Unicode code points, so "Z" < "a" because uppercase letters have lower code point values.


Examples you can copy

Example 1: Check a user command

command="  Quit "

ifcommand.strip().casefold()=="quit":
print("Stopping")
else:
print("Continuing")

Example 2: Validate password confirmation

pw1="mimo123"
pw2="mimo123"

ifpw1==pw2:
print("Match")
else:
print("Does not match")

Example 3: Remove duplicates case-insensitive

tags= ["Python","python","SQL","sql","SQL"]

seen=set()
unique= []

fortintags:
key=t.casefold()
ifkeynotinseen:
seen.add(key)
unique.append(t)

print(unique)

Example 4: Check a prefix or suffix

filename="report_final.pdf"

print(filename.startswith("report_"))
print(filename.endswith(".pdf"))

Example 5: Compare after stripping whitespace

raw="  Hello\t\n"
expected="hello"

print(raw.strip().casefold()==expected)

Example 6: Sort strings case-insensitively

names= ["zoe","Amina","luka"]
sorted_names=sorted(names,key=str.casefold)

print(sorted_names)

Common mistakes and how to fix them

Mistake 1: Using is instead of ==

What you might do:

a="hello"
b="hello"

print(aisb)

Why it breaks: is checks object identity, not string content. It may appear to work sometimes, then fail later.

Correct approach:

print(a==b)

Mistake 2: Comparing raw user input without cleaning

What you might do:

raw="Yes\n"
print(raw=="yes")

Why it breaks: casing and whitespace differ, so the strings are not equal.

Correct approach:

raw="Yes\n"
print(raw.strip().casefold()=="yes")

Mistake 3: Assuming ordering matches human expectations

What you might do:

print("Z"<"a")

Why it surprises you: ordering is based on Unicode code points, not human-friendly collation rules.

Correct approach: normalize before comparing when casing matters.

a="Z"
b="a"

print(a.casefold()<b.casefold())

Troubleshooting

If == returns False unexpectedly, print repr(text) to spot hidden whitespace like \n or \t, then use .strip().

If case-insensitive comparisons fail for some languages, use .casefold() instead of .lower().

If ordering checks look wrong, remember comparisons use Unicode code points. Normalize with .casefold() if casing causes surprises.

If you get TypeError during comparisons, one value may be None or not a string. Convert with str(x) or validate inputs first.


Quick recap

  • Use == to compare strings for equality.
  • Normalize input with .strip() and .casefold() before comparing.
  • Use < and > for ordering checks.
  • Expect Unicode-based ordering like "Z" < "a".
  • Use startswith() and endswith() to check prefixes and suffixes.