Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

Hi. I am trying to replace some characters in python string but it is not working.

I am using this code:

name = abc000

name.replace(“000”,””)

It showed proper output in the python interpreter. Then I tried it in Pycharm by adding the following line

print(name)

but it is not working.

2 Answers

0 votes
by (25.1k points)

You are facing this issue because you are using the replace method incorrectly.

When you call the replace method on a string in python you get a new string with the contents replaced as specified in the method call. You are not storing the modified string but are just using the unmodified string. 

You can do it like this:

name="abc000"

modified_name=name.replace(“000”,””)

print(modified_name)

You can use this video to learn more about python strings and it's methods:

Interested to learn more about Python? Come & join our Python course

0 votes
by (1.9k points)

That indeed seems to be the approach taken for the replace method except you do not assign it to the variable because in Python, strings are immutable.

Here is what you could change your code to:

name = "abc000"  # Put your string in quotes name = name.replace("000", "") print(name)  # Now this will print 'abc' 

Explanation: 

String Quotations:

Now enclose your string inside quotes - either single, ".'s, or double ". 

Assign the Output: 

Now the replace method outputs its new string so make sure to assign the output back to name, or the variable you choose above. 

Print the Output: 

Now when you prompt the user for a name you should now get in return the new string of: This should execute in your Python interpreter and, therefore, within of PyCharm.

Related questions

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...