VS Code (Python 3( 中的此片段:
print("This is it!".replace("is", "are"))
返回奇怪的对我来说输出:
'Thare are it!'
请求是将字符串"is"替换为字符串"are",但没有要求替换字符串"This"?
python 通常在没有请求的情况下进行某种语法更正吗?
提前谢谢你!
由于 "This" 中有 "is",所以它也会被替换。所以代替:
print("This is it!".replace("is", "are"))
用:
print("This is it!".replace(" is ", " are "))
另外,如果您有There it is!
,则可以使用正则表达式:
import regex
re.sub('(W)(is)(W)',r'1are3',"This it is!")
这里提到了这一点
Replace
既不懂单词也不懂语法。它只是搜索给定的字符。 而"这个"里面有"是"。所以它被"ar"取代。
.replace(( 函数将指定的短语替换为另一个指定的短语。 如果未指定任何其他词组,则将替换指定短语的所有匹配项。
.replace 函数的实际语法如下-
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
它的情况也与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'bisb', 'are', "This is it. yes, it is!")
# 'This are it. yes, it are!'