Skip to content

Latest commit

 

History

History
25 lines (19 loc) · 867 Bytes

string-replace-method.md

File metadata and controls

25 lines (19 loc) · 867 Bytes

How to Use the String Replace Method


str.replace()

Python has a built-in function that can be called on a string object to replace all occurrences of a substring with a new substring. You can also optionally pass in the count argument, which controls the number of occurrences to replace.

message = "Hi, I'm a Python Expert!"
new_message = message.replace("Python", "Ruby")  
print(new_message)
#  Hi, I'm a Ruby Expert!
message = "Where can you find what you need to finish the project that you just started."
#  count is 2, so first 2 occurrences will be replaced
new_message = message.replace("you", "I", 2)  
print(new_message)
#  Where can I find what I need to finish the project that you just started.

example link