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)
-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Python,
- Python: Convert Date to DateTime
- How to sort a List using Lambda in Python
- Python matplotlib segmentation fault: 11 macOS Big Sur
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to install Python 3.11 on Mac
- How to flatten a nested list in Python
- Python: Pandas Merge DataFrames on Index Example
- How to Run all Cells at Once Jupyter Notebook
- Python - Convert float to String
- How to add borders to tkinter label text
- How to Exit a Loop in Python Code
- [Python] Fix: ValueError: All arrays must be of the same length
- Sorting an array using Bubble Sort in Python Programming
- How to Unzip a file using Python
- Python: Merge DataFrames Pandas Outer Join Example
- Change label (text) color in tkinter
- Convert Float to String in Python
- Fix: fatal error: No such file or directory compilation terminated
- Python: Access index/counter of a for loop iteration
- Import Other Python Files Examples
- How to install Anaconda on Mac (M1/M2 Mac)
- Python Regular Expression to Find All Matches in List
- How to Read a binary File with Python
- How to disable warnings while Python file execution
- Know current Python Version
More Posts:
- Reduce the size of Tabs on Notepad++ - NotepadPlusPlus
- Python: Split a String into a Dictionary - Python
- Which Python version is bundled with macOS Sonoma 14 by default - MacOS
- How to fix bash ping command not found error - Bash
- How to make a dummy phone call from Android Emulator device - Android
- Get List of AWS SNS Topic Subscriptions using CLI - AWS
- git command to remove/unstage files from staging area - Git
- 9 Mac Keyboard Shortcuts for Taking Screenshots (covers macOS Ventura 13) - MacOS