Extracting and replacing a particular string from a sentence in python
Question:
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
Answers:
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}"
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.
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
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}"
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.