From 7b022e2d72870b7e90dfa4c0413afa2cad4516d4 Mon Sep 17 00:00:00 2001 From: Gokul Manohar <44633074+gokulmanohar@users.noreply.github.com> Date: Fri, 28 Jun 2019 12:30:46 +0530 Subject: [PATCH] Provided a better code. (#33478) * Provided a better code. Updated the code to give desired output. * fix: corrected some verbiage --- .../string-replace-method/index.md | 26 ++++++++++++++++--- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/guide/english/python/string-methods/string-replace-method/index.md b/guide/english/python/string-methods/string-replace-method/index.md index 7a27b2ff28..339a282428 100644 --- a/guide/english/python/string-methods/string-replace-method/index.md +++ b/guide/english/python/string-methods/string-replace-method/index.md @@ -15,10 +15,27 @@ newString = string.replace("is","WAS") print(newString) ``` -Output -```python +Output: + +```shell ThWAS WAS nice. ThWAS WAS good. ``` +As you can see above, the "is" in This is also replaced with Was. + +To prevent this we can use
+ +```python +string = "This is nice. This is good." +newString = string.replace(" is "," WAS ") +print(newString) +``` + +Now the output becomes: + +```shell +This WAS nice. This WAS good. +``` +Here the "is" between whitespaces gets changed to "Was" 2. Replace the first 2 occurrences of `"is"` with `"WAS"` @@ -28,8 +45,9 @@ newString = string.replace("is","WAS", 2) print(newString) ``` -Output -```python +Output: + +```shell ThWAS WAS nice. This is good. ```