How to Replace First Occurrence in Python String?

13-Mar-2023

.

Admin

How to Replace First Occurrence in Python String?

Hi Dev,

In this short tutorial we will cover an how to replace first occurrence in python string. In this article, we will implement a python replace first occurrence in string. This post will give you simple example of how to replace first occurrence of string in python. if you have question about how to replace only first occurrence of string in python then I will give simple example with solution. you will do the following things for python replace first occurrence in string

In this examples, i will add myString variable with hello string. Then we will use replace() function to replace first occurrence from string in python. So, without further ado, let's see simple examples: You can use these examples with python3 (Python 3) version.

Example


main.py

# Declare String Variable

myString = "Hello, This is nicesnippets.com, This is awesome."

# Python Replace Specific Word in String

replaceString = myString.replace("This", "That", 1)

print(replaceString)

Output:

Hello, That is nicesnippets.com, This is awesome.

#Python