If you have a sentence in Python as String and you want to replace the first occurrence of a particular String in it, you can make use of the replace() function from the String class.
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new.
Let's take a look at a few examples.
Example 1: Replace String bad with good.
This example has just one occurrence of good, so we do not need to pass the maxreplace argument.
sentence = "This is a bad idea!" new_sentence = sentence.replace("bad", "good") print(new_sentence)
This is a good idea!
Example 2: Replace 1st $ with USD
In this example, we have two occurrences of string $, so to replace the first occurrence we need to pass the maxreplace argument as 1.
string = "This currency is in $, so you need to pay $49.99" new_string = string.replace("$", "USD",1) print(new_string)
This currency is in USD, so you need to pay $49.99
Facing issues? Have Questions? Post them here! I am happy to answer!
- 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
- Mac: How to Change Terminal Background Color - MacOS
- PowerShell iterate and get all SharePoint sites and sub sites - SharePoint
- Get Button Text onClick Android App - Android
- Python - Convert float to String - Python
- cURL -d Option with Examples - cURL
- Open Large File in Notepad++ (Fix: File is too big to be opened by Notepad++) - NotepadPlusPlus
- Change Mac Default Browser [updated for macOS Ventura] - MacOS
- Enable and reduce background noise in Microsoft Teams with AI-based noise suppression - Teams