Find and replace a value in a string #
You can use the function replace() to find and replace a specific value in a string. Here's how you can call this function:
string.replace(oldvalue, newvalue, count)
The oldvalue is the value you want to replace, and the newvalue is the value you want to replace the oldvalue with. And count tells Python how many times do you want to find and replace the oldvalue. If you leave out the count, Python will replace all the occurrences in the string.
For example:
sentence = "Python is a good programming language"
new_sentence = sentence.replace("good", "great")
print(new_sentence) # Python is a great programming language
sentence_2 = "Ant Bird Bird Cat"
new_sentence_2 = sentence_2.replace("Bird", "Dog", 1) # Only replace Bird once
print(new_sentence_2) # Ant Dog Bird Cat
Exercise #
- Replace all occurrences of A with _ in the variable
sentenceand assign it tonew_sentence - Use the function
replace() - Do not change the first line of the code
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules