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.
# 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()
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".
Let's try changing some statements to check the data types of s and n. This can come in handy when you want to want your script to know for sure what it is receiving from another device.
# convert_try_this from microbit import * sleep(1000) s = "1234" n = 1234 print("s =", s) ts = type(s) # <- change print("Type of s: ts =", ts) # <- change print() print("n = ", n) tn = type(n) # <- change print("Type of n: tn =", tn) # <- change print()
You may have already seen how to get a string and convert it to int in the Computer–micro:bit Talk [1] tutorial. Here, the int result after calculations is also converted back to a string.
# convert_your_turn from microbit import * sleep(1000) s = "1234" print("Before int conversion:") print("s =", s) print() n = int(s) # convert to int n2 = n + n # add s2 = str(n2) # convert back print("After convert, add ints, convert back:") print("s2 =", s2)
Links
[1] https://learn.parallax.com/tutorials/robot/cyberbot/computer-microbit-talk