I'm confused by the string method .replace

Why does it happen when i'm replacing a part of a string (a letter actually in the case) in the second case nothing changes

in> #first case
in>print('Hello, World!'.replace('l','L'))

out>HeLLo, WorLd!

#second case
a = 'Hello, World!'
a.replace('l','L')
print(a)

out>Hello, World!

Upvotes: 1

Views: 64

Answers (2)

Foryah
Foryah

Reputation: 193

Documentation:

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

As @Toto mentioned already, you need to return the value.

Upvotes: 1

Toto
Toto

Reputation: 91488

You have to assign the result of replace to the variable:

a = 'Hello, World!'
a = a.replace('l','L')
print(a)

Upvotes: 5

Related Questions