Home > Net >  Why str.swapcase().swapcase() != str
Why str.swapcase().swapcase() != str

Time:03-30

im just reading the documentation and it is said that for s a given string, this following eq isn’t always true and i’m really wondering why!

s.swapcase().swapcase() == s

(Swapcase do put all the lowercase in uppercase and vice-versa) That make me think about casefold str method in some way but no more is said soo here i am, found nothing on google. Thanks have a great day btw

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".

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