Home > Mobile >  Why str.swapcase().swapcase() != str in Python
Why str.swapcase().swapcase() != str in Python

Time:03-31

I read in the documentation that s.swapcase().swapcase() == s is not always true. Why not? When I read this, I thought this might have something to do with the .casefold method; but I couldn't figure that out and couldn't find anything with an Internet search.

CodePudding user response:

This is because lowercase-to-uppercase (and vice-versa) is not always a 1:1 mapping. Here's an example:

s = "ı"
s.swapcase().swapcase() == s
# => False

This is 'LATIN SMALL LETTER DOTLESS I' (U 0131) used in Turkish. Capitalised version of it is just "I", just like the capitalised version of "i" outside Turkey. (Capitalised version of "i" in Turkey is "İ".) So there are two ways to lowercase "I": the one used in Turkey, and the one used everywhere else. swapcase does not know which one you need.

You would get a similar result for s = "İ": "İ".swapcase() is i, but "i".swapcase() is "I".

Here is another example: s = "ς". That one is 'GREEK SMALL LETTER FINAL SIGMA' (U 03C2), which differs from "σ", 'GREEK SMALL LETTER SIGMA' (U 03C3), in that it is the variant letter only used at the end of the word. But in uppercase, there is no difference, it is always "Σ" — 'GREEK CAPITAL LETTER SIGMA' (U 03A3). swapcase does not check whether the character would be at the end of the word, so "ς".swapcase() becomes "Σ", but "Σ".swapcase() yields the normal sigma, "σ".

CodePudding user response:

I'm going to assume you're using Java In java, there are two ways to compare something - by reference and by value. For objects (like strings), the "==" operator compares the reference of the object. Try:

  • s.swapcase().swapcase().equals(s) or:
  • s.equals(s.swapcase().swapcase())

instead

  • Related