Replace a string in a specific index in a line using python
NickName:dina robert Ask DateTime:2022-05-26T17:55:21

Replace a string in a specific index in a line using python

I'm working on a python project and I want to replace a specific word in a line in a file (text.txt) with another string. Like I have this line <string name="AppName">old string</string> And I want to replace the old string by a variable. That's why I don't want to use replace('old string','new string') I want to replace it depending on an index. Any help is highly appreciated. To be more clear I want to replace whatever is between the first '>' and the second '<' with the new string

Copyright Notice:Content Author:「dina robert」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72389966/replace-a-string-in-a-specific-index-in-a-line-using-python

Answers
Pingu 2022-05-26T10:07:36

This is will replace whatever is between the first '>' and the second '<' with the given string:\ns = '<string name="AppName">old string</string>'\n\ndef replace(s, new):\n if (i := s.find('>')) >= 0:\n if (j := s[i:].find('<')) >= 0:\n s = s[:i+1] + new + s[j+i:]\n return s\n\nprint(replace(s, 'Google'))\n\nOutput:\n<string name="AppName">Google</string>\n\nNote:\nThis would be more typically dealt with using RE",


More about “Replace a string in a specific index in a line using python” related questions