Micro:bit MicroPython: string repetition

In this tutorial we will check how to use the * operator to generate a repetitive sequence of a string. This tutorial was tested on MicroPython running on a micro:bit board.

Introduction

In this tutorial we will check how to use the * operator to generate a repetitive sequence of a string. Using this operator, we can define how many times the original string will be repeated.

The syntax for this operator is the one shown below, where n is the number of times we want the string to be repeated:

originalString * n

This tutorial was tested on MicroPython running on a micro:bit board, although this should work in others boards that can run MicroPython (ESP8266, ESP32, etc..) and in regular Python.

The code

The code for this tutorial will be very simple, since the mention operator takes care of repeating the string for us.

So, we will start by assigning a string to a variable. This will be the base string that will be repeated in the final sequence.

str = "word"

Now, we will apply the * operator with the value 3, meaning we want the original string to be repeated 3 times in the final sequence. We will assign the result to a new variable.

repeatedStr = str*3

Finally, we will print the result to the prompt, so we can confirm the original string was repeated accordingly to what we specified.

print(repeatedStr)

Figure 1 shows the result of running the previous commands on the MicroPython prompt. As can be seen, the original string “word” appears repeated 3 times, forming the string “wordwordword“.

microbit micropython string repetition

Figure 1 – Output of the string repetition commands, on the 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