Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python String isdigit() Method
Next article icon

Thereplace() method replaces all occurrences of a specified substring in a string and returns a new string without modifying the original string.

Let’s look at a simple example of replace() method.

Python
s="Hello World! Hello Python!"# Replace "Hello" with "Hi"s1=s.replace("Hello","Hi")print(s1)

Output
Hi World! Hi Python!

Explanation:Here, "Hello" is replaced by "Hi" throughout the string, resulting in "Hi World! Hi Python!".

Note:Sincereplace()creates a new string, the original string remains unchanged.

Syntax of String replace() Method

string.replace(old, new, count)

Parameters

  • old: The substring we want to replace.
  • new: The new substring that we want to replace with old substring.
  • count (optional): Specifies the maximum number of replacements to perform. If omitted, all occurrences are replaced.

Return Type

  • Returns a new string with the specified replacements made. The original string remains unchanged since strings in Python are immutable.

Using replace() with Count Limit

By using the optional count parameter, we can limit the number of replacements made. This can be helpful when only a specific number of replacements are desired.

Python
s="apple apple apple"# Replace "apple" with "orange" only onces1=s.replace("apple","orange",1)print(s1)

Output
orange apple apple

Explanation: replace()method only replaces the first instance of "apple" because we specifiedcount=1.

Case Sensitivity in replace()

Thereplace() method is case-sensitive, it treats uppercase and lowercase characters as distinct. If we want to replace both cases then we have to use additional logic.

Python
s="Hello, World! hello, world!"# Replace only lowercase 'hello's1=s.replace("hello","hi")print(s1)# Replace only uppercase 'Hello's2=s.replace("Hello","Hi")print(s2)

Output
Hello, World! hi, world!Hi, World! hello, world!



Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp