How to swap case with python regex?

Member

by domenico , in category: Third Party Scripts , 3 months ago

How to swap case with python regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 3 months 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.

Related Threads:

How to make the regex not case sensitive?
How to match regex in python?
How to optimize regex search in python?
How to print matching strings in python with regex?
How to store matched part of regex in python?
How to replace a substring with a regex pattern using regex in python?