George Francis
George Francis

Reputation: 502

Changing lowercase characters to uppercase and vice-versa in Python

I'm trying to write a function which given a string returns another string that flips its lowercase characters to uppercase and viceversa.

My current aproach is as follows:

def swap_case(s):
    word = []
    for char in s:
        word.append(char)

    for char in word:
        if char.islower():
            char.upper()
        else:
            char.lower()

    str1 = ''.join(word)

However the string doesn't actually change, how should I alter the characters inside the loop to do so?

PS: I know s.swapcase() would easily solve this, but I want to alter the characters inside the string during a for loop.

Upvotes: 1

Views: 11464

Answers (6)

Archita Banerjee
Archita Banerjee

Reputation: 1

def swap_case(sentence):
    sentence_list=list(sentence)
    lis=[]
    for i in range(0,len(sentence_list)):
        if sentence_list[i].islower()==True:
            j=sentence_list[i].upper()
            lis.append(j)
        elif sentence_list[i].isupper()==True:
            k=sentence_list[i].lower()
            lis.append(k)
        else:
            lis.append(sentence_list[i])
    final=("").join(lis) 
    return final
sentence=input('Enter Your Sentence: ')
swap_sentence=swap_case(sentence)
print(swap_sentence)

Upvotes: 0

Dhiraj Jayswal
Dhiraj Jayswal

Reputation: 1

def swap_case(s):
    x = ''
    for i in s:
        if i.isupper():
            i = i.lower()
        else:
            i = i.upper()
        x += ''.join(i)
    return x

Upvotes: 0

Kartik Gupta
Kartik Gupta

Reputation: 11

You can use this code:

s = "yourString"    
res = s.swapcase()    
print(res)

Which will output:

YOURsTRING

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

you can use swapcase.

string.swapcase(s)

Return a copy of s, but with lower case letters converted to upper case and vice versa.

Source : Python docs

Upvotes: 4

Pyd
Pyd

Reputation: 6159

>>> name = 'Mr.Ed' or name= ["M","r",".","E","d"]
>>> ''.join(c.lower() if c.isupper() else c.upper() for c in name)
'mR.eD'

Upvotes: 2

John Gordon
John Gordon

Reputation: 33298

def swap_case(s):
    swapped = []

    for char in s:
        if char.islower():
            swapped.append(char.upper())
        elif char.isupper():
            swapped.append(char.lower())
        else:
            swapped.append(char)

    return ''.join(swapped)

Upvotes: 6

Related Questions