When the micro:bit receives strings from other devices, it may need to convert them to other data types to process their data. For example, one micro:bit might use a string to transmit a list of int values. The transmitter has to convert its int values to string representations before sending. The receiver will have to convert the string representations of integers back to int values before it can use them in calculations.
Before converting from int to string and back to int again, let's look at just how differently they behave with an operator that can be used with either type.
Example script: convert_intro
- Enter, name, and save convert_intro.
- Click the Send to micro:bit button.
# convert_intro from microbit import * sleep(1000) s = "1234" n = 1234 print("s =", s) s2 = s + s print("s2 = s + s =", s2) print() print("n = ", n) n2 = n + n print("n2 = n + n =", n2) print()
- Check the results in the serial monitor.
- Verify that the result of adding two instances of "1234" string values to each other is "12341234".
- Verify that the result of adding the two 1234 int values to each other is 2468.
How convert_intro Works
Python recognizes the intended data type when you initialize a variable, based on format.
s = "1234" creates a variable named s of type string, note the enclosing double-quotes.
n = 1234 creates a variable named n of type int; note the lack of double-quotes. (There's no decimal point, so it's not a float.)
The plus + operator performs integer addition on int variables, and so n2 = n + n mathematically adds the two 1234 integers for a result of 2468.
In contrast, that + operator will concatenate two strings—in other words it will join them together. That is why s2 = s + s resulted in "12341234".