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)

Hello, Python!

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

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

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

Mike Alan,25,,New York
Steve Yeli,30,,San Francisco
Stacy John,35,,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)
    for row in reader:
        if len(row) >= 4:  
            city = row[3] 

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:

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