Micro:bit MicroPython: Concatenating strings

In this tutorial we will check how to concatenate strings in MicroPython running on the micro:bit board.


Introduction

In this tutorial we will check how to concatenate strings in MicroPython running on the micro:bit board. If you haven’t yet uploaded the MicroPython firmware to the micro:bit board, please check here how to do it.

Working with strings is something that is useful in every programming language and, in this tutorial, we will cover one of the most basic operations, which corresponds to concatenating strings.

Since Python (and thus, MicroPython) is a very high level language, this kind of basic operations tend to be very simple. In the case of concatenation, we can simply use the + operator to concatenate the strings, as we will be seeing below.


The code

The code for this example will be very simple. We will start by assigning two strings to two different variables. We are going to compose a “Hello World” message by concatenating the two parts of the sentence.

str1 = "Hello"
str2 = "World"

Now, we are going to concatenate the variables using the + operator, already mentioned in the introductory section.

Note that we need a space between the two parts of the sentence. Although we could have included it in any of the previous strings, we will also concatenate the space between them.

concat = str1 + " " + str2

Finally, we will print the result to confirm that the final string was correctly composed.

print(concat)

You can check the result of executing the commands at figure 1 below. As can be seen, we have obtained the full sentence “Hello World” by concatenating the strings.

microbit micropython concat strings.png

Figure 1 – Output of the commands, executed with uPyCraft IDE v1.0.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s