Strings for Exchanging Data

Strings can contain characters that represent numbers.  It is important to understand that a string with "1234" is very different from an int with a value of 1234 that you can add, subtract, multiply, etc.  Instead, "1234" are just the characters that represent the numbers. 

For example, take a string variable named s that contains the characters "1234".  The quotes make it a string.  Without the quotes, n = 1234 creates an int variable that will work in calculations.

s = "1234"  # this makes a string with characters
n = 1234    # this makes an int variable with the value 1234


Radio and Internet devices often have to convert numbers to strings and add names before sending them to other devices.  The devices that receive the string have to find the names and numbers in the string.  In many cases, they also have to convert the string representation of the number back to an int or float so that it can be used in calculations.  For example, here are two names and numbers:

s1 = "First number"
n1 = 1234
s2 = "Second number"
n2 = 5678


One script would have to assemble or packetize the string into this before transmitting:

s = "First number 1234 Second number 5678"


The script running in the receiver might have to parse this data.  In this case, parsing would involve breaking the string into its four substrings: "First number", "1234", "Second number", and "5678".  It might also be up to the receiver to find the "1234" and "5678" substrings and convert them back to int variables that the script can use for calculations.  

Sending and receiving scripts might also have to encrypt the string so that nobody other receivers cannot figure out what the string contains.  Here is a very simple example of an encrypted string.  The transmitter would have to change each character in some way, and the receiver would have to change each character back to the original before it can process the data.  Can you decrypt it and figure out what it really says?

s = "Ifmmp"


In Python, strings can also contain Python statements.  For example, this string:

s = """
print("Hello again!")

...can be sent from one micro:bit to another.  The receiving micro:bit can actually execute the statements inside the string.  This resembles how servers send code to computers to be executed in web pages.  The web content and Javascript to respond when you click buttons are all sent from the server, to your client computer, and then executed by your browser.