2

I'm trying to solve this challenge in hackerrank, which asks to convert all lowercase letters to uppercase letters and vice versa.

I attempt it with the following code:

def swap_case(s):
    length = len(s)
    i=0
    while length:
        if s1[i].isupper():
            s[i].lower()
        elif s[i].islower():
            s[i].upper()
        length-=1
        i+=1
    return s

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

However the string returned is the same as it gets passed into the function. Where is the mistake?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 4
    strings are not mutable. `s[i].upper()` returns an uppercase "copy" of `s[i]`, it doesn't modify `s[i]` itself. You need to create a new string object entirely... – Julien May 19 '17 at 06:49
  • Like @Julien mentioned, you aren't actually changing the original string. Consider using another variable to hold each new update, and return that new variable instead – philip yoo May 19 '17 at 06:52
  • Also, for what its worth, Python already has a builtin function which does this: `str.swapcase()`. – Christian Dean May 19 '17 at 07:08
  • Does this answer your question? [Swapping uppercase and lowercase in a string](https://stackoverflow.com/questions/36247173/swapping-uppercase-and-lowercase-in-a-string) – Georgy Aug 21 '20 at 20:58

11 Answers11

2

The built-in str.swapcase already does this.

def swap_case(s):
    return s.swapcase()
Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
1

As said in comments and othe answers, strings are immutable.

Try following:

s = input("Enter input: ")


def convert(ss):
    # Convert it into list and then change it
    newSS = list(ss)
    for i,c in enumerate(newSS):
        newSS[i] = c.upper() if c.islower() else c.lower()
    # Convert list back to string
    return ''.join(newSS)

print(s)
print(convert(s))

# Or use string build in method
print (s.swapcase())
Priyesh Kumar
  • 2,837
  • 1
  • 15
  • 29
1
def swap_case(s):
    new = ""
    for i in range(len(s)):
        if str.isupper(s[i]):
            new = new + str.lower(s[i])

        elif str.islower(s[i]):
            new = new + str.upper(s[i])

        else:
            new = new + str(s[i])
        
    return (new)

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)
tanmaychk
  • 37
  • 5
0

As @Julien stated in comment upper and lower methods return a copy, and do not change the object itself. See this docs.

EDIT @aryamccarthy reminded me of already existing feature for this kind of task in python: swapcase() method. See more here. Note this also returns a copy of the string.

gonczor
  • 3,994
  • 1
  • 21
  • 46
0

Try this

def swap_case(s):
    l =[]
    str1 = ''
    for i in s:
        if i.isupper():

            l.append(i.lower())
        elif i.islower():
            l.append(i.upper())
        else:
            l.append(i)
    return (str1.join(l))
if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)
HK boy
  • 1,398
  • 11
  • 17
  • 25
sooraj ks
  • 11
  • 2
0

Python-3 in-built swapcase function.

def swap_case(s):
    return s.swapcase()

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

Input:

"Pythonist 3"

Output:

"pYTHONIST 3"
Biman Pal
  • 391
  • 4
  • 9
0
def swap_case(s):
    return s.swapcase()

#or you can use list comprehension 

def swap_case(s):
    new=[ch.lower() if ch.isupper() else ch.upper() for ch in s]
    new=''.join(new)
    return new

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)
  • Welcome to SO! You might take the [Tour](https://stackoverflow.com/tour) and you should (re-)read the help topic [How to Answer](https://stackoverflow.com/help/how-to-answer) to get a feeling on how to contribute. You should always explain your code and your answer, so others can profit from it. "Just code" answers are of very poor quality and might be deleted in the future, what would make your work completely useless. – stackprotector May 20 '20 at 09:33
0
def swap_case(s):
    l = list(s)
    for i in range(len(s)):
        if l[i].islower():
            l[i] = l[i].upper()
        else:
            l[i] = l[i].lower()
    k = "".join(map(str,l))
    return k
  • or you can also use return s.swapcase() – Abhinav Mishra Aug 02 '20 at 08:31
  • 2
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Aug 02 '20 at 08:55
  • 2
    Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what the code does and how it answers the question, so that it is also useful for other users with similar a problem, as well as the OP – Greenonline Aug 02 '20 at 08:56
0
def swap_case(s):
    a=" "
    for i in s:
        if i==i.lower():
            a=a+(i.upper())
        else:
            a=a+(i.lower())
    return (a)
0
import string

upalf = string.ascii_uppercase

lowalf = string.ascii_lowercase

def swap_case(s):
    new = ""
    for i in s:
        if i in upalf:
            new += i.lower()
        elif i in lowalf:
            new += i.upper()
        else:
            new += i
    return new

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

**In this problem, I used the module called "string", inside of it there are attributes that have the Uppercase letter, and lowercase letters **

-1
def swap_case(s):
    list_s= list(s)
    for index,char in enumerate(list_s):
        if char == char.lower():
            list_s[index] =char.upper()
        else:
            list_s[index]= char.lower()
            s = ''.join(list_s)
    return s

string = 'HackerRank.com presents "Pythonist 2".'
print(swap_case(string))
Ruli
  • 2,592
  • 12
  • 30
  • 40
9 Rules
  • 9
  • 2