2

This snippet in VS Code (Python 3):

print("This is it!".replace("is", "are"))

returns strange for me output:

'Thare are it!'

The request was to replace string "is" with string "are", but wasn't requested to replace string "This"?

Is it usual for python to make some kind of grammar corrections without requests?

Thank you in advance!

petezurich
  • 9,280
  • 9
  • 43
  • 57
Chubini
  • 115
  • 4

4 Answers4

3

Since there is "is" in "This" , that too gets replaced. So instead of :

print("This is it!".replace("is", "are"))

use:

print("This is it!".replace(" is ", " are "))

Also if you have There it is!, you can use regex:

import regex
re.sub('(\W)(is)(\W)',r'\1are\3',"This it is!")

This is beautifully mentioned here

Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
  • 2
    Note that this is also not going to be a grammatical replacement either, it is just precluding a class of replacements. But it is not covering all corner cases, e.g. `There it is!` will not be touched. – norok2 May 14 '20 at 14:11
2

Replace don't know words nor grammar. It just searches for the characters given. And "This" has "is" in it. So it gets replaced by "ar".

Banana
  • 2,295
  • 1
  • 8
  • 25
1

The .replace() function replaces a specified phrase with another specified phrase. All occurrences of the specified phrase will be replaced, if nothing else is specified.

the actual syntax for .replace function is as follows-

string.replace(oldvalue, newvalue, count)

oldvalue - The string to search for
newvalue - The string to replace the old value with
count(Optional)- A number specifying how many occurrences of the old value you want to replace. By Default is all occurrences

It happens similarly to Java as well, its not about python only, JAVA Syntex is-

public String replace(char oldChar, char newChar)  
and  
public String replace(CharSequence target, CharSequence replacement)  

check out this example-

public class ReplaceExample1{  
public static void main(String args[]){  
String s1="javatpoint is a very good language";  
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'  
System.out.println(replaceString);  
}} 

this will give result as follows in java

jevetpoint is e very good lenguege

if you want to replace "is" for your case you should use " is " it means you are using spacebar as an element for your string thus the required result will come-

print("This is it!".replace(" is ", " are "))
output- This are it!
Anubhav
  • 48
  • 5
1

The clean way to do it is to use a regular expression with word boundaries \b before and after your word:

import re

re.sub(r'\bis\b', 'are', "This is it. yes, it is!")
# 'This are it. yes, it are!'
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50