strring ="My name is David and I live is India" # correct the grammer using find and replace method
new_str=strring.find("is") # find the index of first "is"
print(new_str)
fnl_str=strring.replace("is","in") # replace "is" with "in" ( My name is David and I live in India )
print(fnl_str)
Asked
Active
Viewed 30 times
1
-
Explain the complete issue or do `strring = strring.replace('live is','live in')` – Yash Kumar Atri Sep 30 '18 at 16:25
-
1Take a look at https://stackoverflow.com/questions/9943504/right-to-left-string-replace-in-python – Ruzihm Sep 30 '18 at 16:25
-
If you have something else in mind then look at https://stackoverflow.com/q/46705546/4320263 – Yash Kumar Atri Sep 30 '18 at 16:27
2 Answers
1
Maybe str.rpartition() solves the case here, though not a general solution:
strring = "My name is David and I live is India"
first, sep, last = strring.rpartition('is')
print(first + 'in' + last)
# My name is David and I live in India
Austin
- 25,759
- 4
- 25
- 48
0
You could .split() the string then use enumerate to create a list of the indices of items containing the word is. Then you can take the second index in that list and use that index to change the item to in. Then use ' '.join() to put it back together
s = "My name is David and I live is India"
s = s.split()
loc = []
for idx, item in enumerate(s):
if item == 'is':
loc.append(idx)
s[loc[1]] = 'in'
print(' '.join(s))
My name is David and I live in India
vash_the_stampede
- 4,590
- 1
- 8
- 20