Shoaib Wani
Shoaib Wani

Reputation: 96

Why does replace not replace?

code:

a = 'g'
b = a.title()
b.replace(b, a)
print(b)

output: G

I think the output should be 'g' lowercase as the replace statement replaces the uppercase 'G' to lowercase one.

I am trying to solve a challenge in which I have to capitalize a string but not the one that starts with numerals?

Upvotes: 1

Views: 129

Answers (3)

Jack Lilhammers
Jack Lilhammers

Reputation: 1247

Strings in python are immutable.
Functions that would change the string, return a new one instead.

You can read the reasons behind this choice in many articles, like
https://www.educative.io/edpresso/why-are-strings-in-python-immutable

Upvotes: 2

T1Berger
T1Berger

Reputation: 505

The output of replace need ot be reassign - because replace gives you a copy with the replaced changes - so it isnt in place!

a = 'g'
b = a.title()
b = b.replace(b, a)
print(b)

Upvotes: 2

Nidal Barada
Nidal Barada

Reputation: 393

You have to assign the value of b.replace(b, a) to the variable b before you print it.

a = 'g'
b = a.title()
b = b.replace(b, a)
print(b)

Output:

g

Upvotes: 3

Related Questions