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.
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 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.
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“.
Figure 1 – Output of the string repetition commands, on the uPyCraft IDE v1.0.