Home > Net >  Replace a string in a specific index in a line using python
Replace a string in a specific index in a line using python

Time:05-26

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

CodePudding user response:

This is will replace whatever is between the first '>' and the second '<' with the given string:

s = '<string name="AppName">old string</string>'

def replace(s, new):
    if (i := s.find('>')) >= 0:
        if (j := s[i:].find('<')) >= 0:
            s = s[:i 1]   new   s[j i:]
    return s

print(replace(s, 'Google'))

Output:

<string name="AppName">Google</string>

Note:

This would be more typically dealt with using RE

CodePudding user response:

Use regex replace

from re import sub

string = "<string name='AppName'>Google</string>"
# anything between the >< will be converted to new_var_string
replace_string = sub(r'>\w <', f'>{new_var_string}<', string)

example 1:

from re import sub

string = "<string name='AppName'>Google</string>"
# anything between the >< will be converted to new_var_string
new_var_string = 'youtube'
replace_string = sub(r'>\w <', f'>{new_var_string}<', string)
print(replace_string)

output:

<string name='AppName'>youtube</string>

example 2:

from re import sub

string = "<string name='AppName'>Goo1231gl125125e</string>"
# anything between the >< will be converted to new_var_string
new_var_string = 'youtube'
replace_string = sub(r'>\w <', f'>{new_var_string}<', string)
print(replace_string)

output:

<string name='AppName'>youtube</string>
  • Related