Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why str.swapcase().swapcase() != str in Python

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.

like image 932
Obed Lacroix Avatar asked Sep 06 '25 03:09

Obed Lacroix


1 Answers

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

like image 127
Amadan Avatar answered Sep 08 '25 00:09

Amadan