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:
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.csvName,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)
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!