提取并替换Python中句子中的特定字符串

huangapple go评论61阅读模式
英文:

Extracting and replacing a particular string from a sentence in python

问题

"Say I have a string,

s1="Hey Siri open call up duty"

and another string

s2="call up duty".

Now I know that "call up duty" should be replaced by "call of duty".

Say s3="call of duty".

So what I want to do is that from s1 delete s2 and place s3 in its location. I am not sure how this can be done. Can anyone please guide me as I am new to python. The answer should be

"Hey siri open call of duty"

Note--> s2 can be anywhere within the string s1 and need not be at the last every time

英文:

Say I have a string,

s1="Hey Siri open call up duty"

and another string

s2="call up duty".

Now I know that "call up duty" should be replaced by "call of duty".

Say s3="call of duty".

So what I want to do is that from s1 delete s2 and place s3 in its location. I am not sure how this can be done. Can anyone please guide me as I am new to python. The answer should be

"Hey siri open call of duty"

Note--> s2 can be anywhere within the string s1 and need not be at the last everytime

答案1

得分: 3

在Python中,字符串具有replace()方法,您可以轻松使用它来替换子字符串s2为s3。

s1 = "Hey Siri open call up duty"
s2 = "call up duty"
s3 = "call of duty"

s1 = s1.replace(s2, s3)
print(s1)

这应该对您有所帮助。对于更复杂的替换,re模块可能会有所帮助。

英文:

In python, Strings have a replace() method which you can easily use to replace the sub-string s2 with s3.

s1 = "Hey Siri open call up duty"
s2 = "call up duty"
s3 =  "call of duty"

s1 = s1.replace(s2, s3)
print(s1)

This should do it for you. For more complex substitutions the re module can be of help.

答案2

得分: 1

s2= "call up duty"
s3= "call of duty"
s1= f"Hey Siri open {s2}"

英文:

You can use f string to use different string blocks in the string.

s2= "call up duty"
s3= "call of duty"
s1= f"Hey Siri open {s2}"

huangapple
  • 本文由 发表于 2023年2月16日 15:21:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定