Java .replace() RegEx alternative in Python Programming


If you come from a Java background to Python, you might be looking for an alternative for .replace() to work with RegEx.

In the module that you need is re, this module is full of regular expression matching operations similar to Pattern and Matcher utils in Java.

Let us take a look at some examples.

Example: Let's say you have a string "Hello, Java!" that you want to replace Java with Python

import re

message = "Hello, Java!"
new_message = re.sub(r"Java", "Python", message)
print(new_message)
Output:

Hello, Python!

We have made use of the re.sub() method

Syntax:
re.sub(pattern, repl, string, count=0, flags=0)

Now let us take a look at a practice example of working with CSV files.

data.csv
Name,Age,Email,City
Mike Alan,25,mike@example.com,New York
Steve Yeli,30,steve@example.com,San Francisco
Stacy John,35,stacy@example.com,Chicago

Now let's try to extract the city names from the data.csv

import csv

csv_file = 'data.csv'

with open(csv_file, 'r') as file:
    reader = csv.reader(file)
    next(reader) 
    
    for row in reader:
        if len(row) >= 4:  
            city = row[3] 
            print(city)

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap