Which string method in Python is used to replace parts of a string?
a) replace()
b) swap()
c) change()
d) substitute()
Answer:
a) replace()
Explanation:
The .replace()
method in Python is used to replace occurrences of a specified substring within a string with another substring. It returns a new string with the replacements made.
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text) # Prints "Hello, Python!"
This method is useful for tasks like text substitution, data cleaning, and formatting, where you need to modify specific parts of a string.
Using the .replace()
method allows you to efficiently alter strings without manually changing each instance of a substring.