-3

Here is my code snippet. What am I doing wrong? Not able to replace the string.

f = open("template.html", "r")
 lines = f.read()
 string = '''<header > 
 <h2 align="center"> High </h2> 
 <h4> </h4> 
 </header> '''
 if string in lines:
    print lines
    lines.replace("<header >", "<header style=background-color:red >")
    print lines
Biffen
  • 6,249
  • 6
  • 28
  • 36
user3640472
  • 115
  • 9
  • 4
    Possible duplicate of [Why doesn't calling a Python string method do anything unless you assign its output?](https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) – Biffen Mar 20 '18 at 07:51
  • Python strings are *immutable* - read-only if you like. So no string methods can alter the string in place, they have to return a new string. – cdarke Mar 20 '18 at 07:56
  • @user3640472, it is working for you ? – Mihai Alexandru-Ionut Mar 21 '18 at 07:08

2 Answers2

0

After you use replace you need to save it back to the variable.

Ex:

lines = lines.replace("<header >", "<header style=background-color:red >")
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

replace method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.

So you need to update your lines variable's value. Python strings are immutable like in another programming languages like C#, Java, Javascript, PHP, etc.

lines = lines.replace("<header >", "<header style=background-color:red >")
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128