How to swap case with python regex?

Member

by domenico , in category: Third Party Scripts , 14 days ago

How to swap case with python regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 13 days ago

@domenico 

You can use Python's re module to swap the case of characters within a string using regular expressions. Here's an example code that demonstrates how to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import re

def swap_case(text):
    return re.sub(r'[a-zA-Z]', 
                  lambda x: x.group().lower() if x.group().isupper() else x.group().upper(), 
                  text)

# Example usage
text = "Hello World"
swapped_text = swap_case(text)
print(swapped_text)  # Output: hELLO wORLD


In this code, the swap_case function takes a text input and uses the re.sub method to substitute each alphabetic character in the text with its opposite case using a lambda function. The lambda x: x.group().lower() if x.group().isupper() else x.group().upper() is used to check if the character is uppercase, then convert it to lowercase, and vice versa.