1

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?

1
  • 9
    replace is not "in place" it returns the replaced string. so do something like c = b.replace(b, a) Commented Feb 10, 2021 at 10:50

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.