Python 为什么replace()函数在未使用正确参数请求时返回语法编辑的结果?

Python 为什么replace()函数在未使用正确参数请求时返回语法编辑的结果?,python,python-3.x,string,function,replace,Python,Python 3.x,String,Function,Replace,VS代码(Python 3)中的此代码段: 为我返回奇怪的输出: 'Thare are it!' 请求将字符串“is”替换为字符串“are”,但未请求替换字符串“This” python通常在没有请求的情况下进行某种语法更正吗 提前谢谢你 既然“This”中有“is”,那么它也会被替换掉。因此,不是: print("This is it!".replace("is", "are")) 使用: 如果你有,它也在那里,您可以使用正则表达式: import regex re.sub('(\W)(i

VS代码(Python 3)中的此代码段:

为我返回奇怪的输出:

'Thare are it!'
请求将字符串“is”替换为字符串“are”,但未请求替换字符串“This”

python通常在没有请求的情况下进行某种语法更正吗

提前谢谢你

既然“This”中有“is”,那么它也会被替换掉。因此,不是:

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

如果你有
,它也在那里,您可以使用正则表达式:

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

这一点提到得很漂亮

Replace
既不懂单词也不懂语法。它只搜索给定的字符。 “这个”在里面。因此,它被“ar”替换。

函数的.replace()将一个指定短语替换为另一个指定短语。 如果未指定其他内容,则将替换指定短语的所有匹配项

.replace函数的实际语法如下-

Java也有类似的情况,不仅仅是python,Java Syntex是-

public String replace(char oldChar, char newChar)  
and  
public String replace(CharSequence target, CharSequence replacement)  
看看这个例子-

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);  
}} 
这将在java中产生如下结果

jevetpoint is e very good lenguege
如果您想为您的案例替换“is”,您应该使用“is”,这意味着您正在使用空格键作为字符串的元素,因此将得到所需的结果-

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

最简单的方法是在单词前后使用带单词边界的正则表达式
\b

import re

re.sub(r'\bis\b', 'are', "This is it. yes, it is!")
# 'This are it. yes, it are!'

在你看到语法的地方,计算机只看到字符序列……这个
的最后两个字母是什么??好的,谢谢大家!!!我的秋天!!!!注意,这也不是语法上的替换,它只是排除了一类替换。但它并没有覆盖所有角落的案例,例如,
就在这里将不会被触摸。
jevetpoint is e very good lenguege
print("This is it!".replace(" is ", " are "))
output- This are it!
import re

re.sub(r'\bis\b', 'are', "This is it. yes, it is!")
# 'This are it. yes, it are!'