Your Turn: Careful with string.replace

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).

Example script: other_methods_your_turn

  • Enter, name, and save other_methods_your_turn.  
  • Click the Send to micro:bit button.
# 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()
  • Check the results in the serial monitor.
  • Verify that the second string causes characters to be misspelled.
  • Verify that the third string replaces both instances of  " a " as a word without affecting the spelling of characters.
  • Verify that only the first instance of " a " was replaced with " the " in the last string.