-2

this script is supposed to swap case in words but the result is really weird and doesn't make sense

def swap_case(s):
for i in range(len(s)):
    if s[i].islower():
        s= s.replace(s[i],s[i].upper())
    elif s[i].isupper():
        s= s.replace(s[i],s[i].lower())
    else:
        pass

example

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Arian
  • 11
  • 4

4 Answers4

4

First of all consider using inbuild swapcase function Otherwise, you can use join function

E.g.

s = "hELLO wORLD"
# inbuilt
print(s.swapcase())
# join
print(''.join([ss.lower() if ss.isupper() else ss.upper() for ss in s]))

which gives you

output

Jackson
  • 1,213
  • 1
  • 4
  • 14
3

You're going through each letter in the string, then replacing all instances of that letter. That means that if there's an even amount of a letter, the case won't be changed.

Also, a method, swapcase, already exists for this.

>>> 'Hello World!'.swapcase()
'hELLO wORLD!'
duckboycool
  • 2,425
  • 2
  • 8
  • 23
  • I was thinking of this... but reading *this script is supposed to change lower case **words** into upper case and vice versa* (emphasis mine) - I'm not sure it's correct - the description and the actual attempted code are somewhat contradictory... – Jon Clements Apr 29 '20 at 17:00
  • @JonClements I doubt they'd be iterating through each letter in the word and trying to replace if that were the case. I guess we'll see what they say though. – duckboycool Apr 29 '20 at 17:04
0

Here is the solution for your problem-->

def swap_case(s):
    k=''
    for i in range(len(s)):
        if s[i].islower():
            k+=s[i].upper()
        elif s[i].isupper():
            k+=s[i].lower()
        else:
            pass
    print(k)
MrFamousKK
  • 34
  • 5
  • 2
    It is more efficient to build a list and `join` it at the end – Thierry Lathuille Apr 29 '20 at 17:11
  • it works but it should be like this to work perfectly . thanks :) – Arian Apr 29 '20 at 17:13
  • def swap_case(s): k='' for i in range(len(s)): if s[i].islower(): k+=s[i].upper() elif s[i].isupper(): k+=s[i].lower() else: k+=s[i] print(k) swap_case("Hello World") – Arian Apr 29 '20 at 17:14
  • Yes. I just thought i would return him the function which is a bit less complicated and he would understand it easily. Your suggestion is very good ! – MrFamousKK Apr 29 '20 at 17:14
0

Solution with Python

Case Swapping can be achieve using a python built-in function called swapcase if you want to do this manually then here is the code.

result = ''
    for element in (s):
        if element.isupper():
            result += element.lower()
        else:
            result += element.upper()  
        print(result)