5

I would like to write a function in Python that takes a string which has lower and upper case letters as a parameter and converts upper case letters to lower case, and lower case letters to upper case.

For example:

>>> func('DDDddddd')
'dddDDDDD'

I want to do it with strings but I couldn't figure out how.

Sam Mussmann
  • 5,883
  • 2
  • 29
  • 43
billwild
  • 173
  • 1
  • 3
  • 12
  • 2
    Welcome to Stack Overflow! It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, stack traces, compiler errors - whatever is applicable). The more detail you provide, the more answers you are likely to receive. – Martijn Pieters Nov 16 '12 at 13:44
  • The question is perfectly clear. It's also perfectly clearly a duplicate of [Invert case of a string](https://stackoverflow.com/questions/26385823/invert-case-of-a-string). – Karl Knechtel Aug 29 '22 at 14:13

2 Answers2

25

EDIT - Way simpler than my original answer, and supports both ASCII and unicode. Thanks commenters.

a = 'aBcD'
a.swapcase()
>> AbCd

Original answer - disregard

a = 'aBcD'
''.join(map(str.swapcase, a))
>> AbCd

This will map the str.swapcase() function to each element of the string a, swapping the case of each character and returning an list of characters.

''.join() will join each character in the list into a new string.

Aesthete
  • 18,622
  • 6
  • 36
  • 45
1

You should look into string.maketrans to create a translation table that could be used with str.translate. Other constants which will probably be useful are string.ascii_lowercase and string.ascii_uppercase.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • i tried to do it with x.islower() or x.lower() but it print all uppercase or all lowercase. İ want to turn upper to lower, lower to upper – billwild Nov 16 '12 at 13:50
  • @user1829771 -- you could do it that way too. You'd just need to build a list and then join it with `str.join`. e.g. `''.join(['a','b','c'])` yields `'abc'` – mgilson Nov 16 '12 at 13:52