-1

I have a long string which opens and closes with 3 double quotes ("""). When I use the .replace function on it, it doesn't work (nor does it return an error or anything). It appears to run the code and then when I print the updated string, it hasn't actually changed.

surnames="""
Smith    
Jones    
Taylor
"""

Say I wanted to replace the uppercase 'S' in 'Smith' with an 'A' for example:

surnames.replace("S", "A")

It doesn't work! Is it even possible to do these operations on long strings in Python?

2 Answers2

2

The way you write your string literal doesn't matter. A str is str, "long strings" is not a thing in Python.

Where your code goes wrong, is the fact that a str is immutable and that the replace method returns a new string with the result of the replace operation. So you have to write:

surnames = surnames.replace("S", "A") 

if you want to make surnames contain the new string.

Irmen de Jong
  • 2,739
  • 1
  • 14
  • 26
0

The program:

s = "SMMMM" \
    "AAAAAAAAAAAAAAA"

print(s.replace("S", "A"))
print(s)

The Output:

AMMMMAAAAAAAAAAAAAAA
SMMMMAAAAAAAAAAAAAAA
youDaily
  • 1,372
  • 13
  • 21