As mentioned on the previous page, the string.replace() method is designed to find and replace all parts of a string that match the substring. If there’s only going to be one match, great. What if you instead want to replace the word “a” with “the” though?. If the original string contains the word “characters”, it might get converted to “chtherthecters”. Yikes!
To solve this, the substring could be set to " a " with spaces before and after. Likewise, the replacement string is should be " the ", also with spaces before and after.
And let’s say you only want to replace the first instance of “a”. Another approach would be to use string.replace(" a ", " the ", 1).
# other_methods_your_turn from microbit import * sleep(1000) string = "This is a string. It is a sequence of characters!" print("Original string:", string) print() new_string = string.replace("a", "the") print("Unexpected results with 'a' -> 'the':") print("new_string =", new_string) print() new_string = string.replace(" a ", " the ") print("Better results with 'a' -> 'the':") print("new_string =", new_string) print() new_string = string.replace(" a ", " the ", 1) print("Selective results with 'a' -> 'the':") print("new_string =", new_string) print()