为什么当函数replace()没有使用适当的参数请求时,会返回语法编辑过的结果?

问题描述 投票:2回答:4

在VS Code (Python 3)中的这段代码。

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

对我来说返回的是奇怪的结果。

'Thare are it!'

请求将字符串 "is "替换为字符串 "are",但没有请求替换字符串 "This"?

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

先谢谢你

python python-3.x string function replace
4个回答
3
投票

因为在 "This "中有 "is",所以也被替换了。所以用:

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

使用:"is"。

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

如果你有 There it is!你可以使用regex。

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

这一点说得很好 此处


2
投票

Replace 不懂单词,也不懂语法。它只是搜索所给的字符.而 "这个 "里面有 "是"。所以它被 "ar "所取代。


1
投票

.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!

1
投票

最简单的方法是使用一个有字界的正则表达式。\b 在你说话前后。

import re

re.sub(r'\bis\b', 'are', "This is it. yes, it is!")
# 'This are it. yes, it are!'
© www.soinside.com 2019 - 2024. All rights reserved.