String Surgery

In cybersecurity situations, your script might need to modify a string it receives.  One method for modifying strings is to create a larger string by adding smaller strings together.  This process is called concatenation.

Example script: string_surgery_intro

  • Enter this script and save it as string_surgery_intro.  
  • Flash the script into the micro:bit.
# string_surgery_intro

from microbit import *


s1 = "Have "
s2 = "a "
s3 = "nice "
s4 = "day."

s = s1 + s2 + s3 + s4

print("s = ", s)
  • Open the terminal and verify that it displays s = "Have a nice day."

How string_surgery_intro Works

The script starts with 4 separate strings: s1, s2, s3, and s4, and addes them together.  Addition with string objects is very different from the addition in the int and float objects you are probably familiar with.  When string objects are added, they are combined.  So, "abc" + "def" results in a string "abcdef".  In our case, s = s1 + s2 + s3 + s4 results in a new string variable s that refers to the "Have a nice day." string.