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, name, and save string_surgery_intro.  
  • Click the Send to micro:bit button.
# string_surgery_intro

from microbit import *

sleep(1000)

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

s = s1 + s2 + s3 + s4

print("s = ", s)
  • Check the results in the serial monitor.
  • 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.