How to turn upper-case and lower-case letters into upper-case letters in Python?

Asked

Viewed 6,345 times

2

What was the name of the Python method that turns upper-case and lower-case letters into upper-case letters in the same string?

For example:

texto = "AquI TeM umA StrinG"
saída = "aQUi tEm UMa sTRINg"

3 answers

7


texto.swapcase()
#'aQUi tEm UMa sTRINg'
  • I remember that I had this method, only now I lacked memory.

  • @Alexfeliciano if the answer helped you, mark it as 'accepted'!

  • Thanks, it really helped. I knew there was this rsrsrs function.

7

I don’t believe you have a specific function for that. But like good language worth its salt, it has two functions to work with this type of problem.

The first function is to .upper() which returns the uppercase character and the second is .lower() which does the reverse. They technically do not treat the character to ignore or reverse the state, but we have other functions that do the checking.

To check if a character is already uppercase, just use the function .isupper() and the reverse .islower().

So how can we implement this?

Let’s create the function reverter_string that takes as argument a string, it must return the "inverse of the string" (in the case of uppercase). Basically, let’s iterate each character by checking if it’s uppercase, if it is, let’s make it lowercase, and vice versa.

The algorithm applied is this:

def reverter(string):
   retorno = ''
   for caractere in string:
      if caractere.isupper():
         retorno += caractere.lower()
      else:
         retorno += caractere.upper()
   return retorno

This is basically the code. The question is: the code is too big! In this case, we can use a very useful Python function (which there must also be in some many languages), the function map(). This function maps each item of an object that can be iterated (such as strings, tuples, lists, dictionaries) and returns a final result by performing a function on each one.

In this case, the revert string function will become just that:

def reverter(string):
   return ''.join(map(lambda c: c.upper() if c.islower() else c.lower(), string))

The code still got confused?

The function map takes a function and a string, and parses each character using the function of the first argument (which uses the same algorithm as the previous function), and returns a map Object, that resembles an iterator.

What does that mean?

It means I need to join the characters with a join, so that it is there. Otherwise I will have a list, instead of a string in return.

That’s it...

EDIT:

There’s a specific function for that, called .swapcase(). Simply apply:

string = "python É uma LINGUAGEM mágica"
string.swapcase()
# retorna: 'PYTHON é UMA linguagem MÁGICA'
  • After I answered I went to read in the official Python documentation, and there really is a function. There is the function .swapcase(), can be found at this link: https://docs.python.org/3/library/stdtypes.html#str.swapcase

6

The method you seek is swapcase. Only by complementing the other answers, the documentation mentions that not always s.swapcase().swapcase() == s. That is, if you flip the upper and lower case, and then do this operation again, the result will not always be the original string.

An example where this happens:

s = "ς"
print(s.swapcase())
print(s.swapcase().swapcase())

The exit is:

Σ
σ

This happens because both the character ς (GREEK SMALL LETTER FINAL SIGMA) REGARDING character σ (GREEK SMALL LETTER SIGMA) are used to represent the letter sigma minuscule (if I’m not mistaken the first is only used at the end of a word, but since I’m not fluent in Greek, then there may be more rules involved).

For both, the capital version is character Σ (GREEK CAPITAL LETTER SIGMA), then the first swapcase() results in Σ. But in doing the second swapcase, the result is σ.

Interestingly, if you have more than one character (forming a word), the above situation does not happen:

s = "πς"
print(s.swapcase())
print(s.swapcase().swapcase())

The exit is:

ΠΣ
πς

When the character ς is not alone, the two calls from swapcase result in the original character. Probably because now he’s at the end of a word (but I don’t know why the behavior is different when he’s alone). And obviously I don’t even know if the string above is a valid Greek word (I would guess that no). Anyway, this shows how the concepts of upper and lower case letters are not always so obvious, and knowing the language the strings are in helps a lot when dealing with the same.


Another example is the german character ß, that when converted to uppercase, it becomes "SS". And when converting back to lowercase, the "SS" becomes "ss":

s = "ßabc"
print(s.swapcase())
print(s.swapcase().swapcase())

Exit:

SSABC
ssabc

Of course, if you will only work with Portuguese texts (or any language that only uses the Latin alphabet), these problems will not occur. But it’s interesting to know that this kind of thing can happen, depending on the case.

This response from Soen has a more complete list of characters with which this type of situation occurs.

  • 1

    Thank you for supplementing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.