How do we combine two activities – say one, remove numbers, special characters and two, convert uppercase to lowercase letters, and back

Question:

Typed code : How to combine the two parts in the code for 1 output >>

s= input()
   
def swap_case(s):
    word = []
    for char in s:
      if char.islower():
        word.append(char.upper())
      else:
        word.append(char.lower())
    str1 = ''.join(word)
    return str1
    
    import re
    new_string = re.sub('[^A-Za-z]+', '', s)
    return new_string

print(swap_case(s))
Asked By: Abhijit Ganguly

||

Answers:

You can first remove the characters that you want, and then do the swapping.

import re

s = input()

def swap_case(str):
    word = []
    for char in re.sub('[^A-Za-z]+', '', str):
        if char.islower():
            word.append(char.upper())
        else:
            word.append(char.lower())
    return ''.join(word)

print(swap_case(s))

Or in short:

import re

s = input()

def swap_case(str):
    return re.sub('[^A-Za-z]+', '', str).swapcase()


print(swap_case(s))
Answered By: The fourth bird
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.