Strings¶
Working with text in Python. You can join, slice, multiply, replace parts of string, trim and many other operations on the string.
Joining strings¶
Join, or concatenate, strings with the + sign:
display.scroll('hello ' + 'world')
You cannot join numbers and strings together; you must first convert the number to a string using the str() function if you want to do that.
x = temperature
if temperature < 6:
display.scroll("Cold" + str(temperature))
Indexing Strings¶
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one.
word = 'microbit'
display.show(word[0]) # character in position 0, m
sleep(1000)
display.show(word[5]) # character in position 5, b
Indices may also be negative numbers, to start counting from the right:
word = 'microbit'
display.show(word[-1]) # last character, t
sleep(1000)
display.show(word[-2]) # second to the last character, i
Note that since -0 is the same as 0, negative indices start from -1.
Slicing strings¶
You can slice strings using the numerical position of characters, counting from 0.
| range | display.scroll('hello'[1:3]) |
|---|---|
| single character | display.scroll('hello'[0]) |
| after | display.scroll('hello'[2:]) |
| before | display.scroll('hello'[:2]) |
You can slice string variables in the same way. This slices the string from character position 1 to 3 and shows ‘el’:
word = 'hello'
display.scroll(word[1:3])
Multiplying strings¶
You can repeat strings by multiplying them:
display.scroll('hello' * 3)
The example above scrolls ‘hello’ on the LED display 3 times with no spaces.
Multiplying strings like this can be useful for printing simple bar charts in the serial console:
while True:
print('X' * temperature())
sleep(1000)
Replacing parts of strings¶
Use replace() to swap out sections of a string by their contents:
.. code-block:: python
display.scroll(‘Hello world’.replace(‘Hello’, ‘Hola’))
This shows ‘Hola world’.
Trimming strings¶
Use strip() to trim characters from the start or end of a string:
display.scroll('wowow'.strip('w'))
This removes ‘w’ from the start and end of the string, so ‘owo’ is shown.
You can also use this function to strip out spaces at the start or end of a string. lstrip() and rstrip() will also trim spaces from the left or right of a string.
Length of a string¶
Use len() to find the length of a string:
display.scroll(len('hello'))
This shows 5 because the string is 5 characters long.
Convert case¶
You can convert strings to upper or lower case.
display.scroll('hello'.upper())
display.scroll('HELLO'.lower())
Searching strings¶
You can find where the first and last occurrences of a character (or characters) are.
You can locate the position of the first occurrence of a character or set of characters with find(). Use rfind() to find the last occurrence of a character or set of characters.
Here 7 is shown, because the last occurrence ‘i’ is at character position 7:
display.scroll('micro:bit'.find('i'))
display.scroll('micro:bit'.rfind('i'))
Counting occurrences¶
Use count() to count the number of times a character or set of characters appear in a string:
display.scroll('micro:bit'.count('i'))
This will show 2 because the letter ‘i’ occurs twice in ‘micro:bit.’
You can also use count() to count the number of times a word appears in a string. This will show 2:
Testing strings¶
You can test strings to discover what kind of characters they contain, or if they contain certain characters.
if 'hello'.islower():
display.scroll('lower case')
You can test string variables the same way:
myString = 'hello'
if myString.islower():
display.scroll('lower case')
Placeholders¶
You can put placeholders in strings that are then replaced with the values of variables:
name = 'Peta'
score = 17
time = 23.67
display.scroll('Hi %s you scored %i points in %1.2f seconds' % (name, score, time))
The output in this example is ‘Hi Peta you scored 17 points in 23.67 seconds’
It uses %1.2f to specify that two decimal places should be displayed.
Use %s for strings, %i for integers and %f for floating point numbers.
ASCII value of character¶
ASCII is a system used for encoding letters and symbols as numbers when they’re stored in a computer system.
Use ord() to discover the ASCII value of a character:
display.scroll(ord('a'))
In this example 97 is shown because the letter ‘a’ is encoded in ASCII with the number 97.
Print character from ASCII value¶
Use chr() to convert a numerical ASCII value to a character string:
display.scroll(chr(98))
In this example the letter ‘b’ is shown.
Using chr() and ord() in Python programs can be useful when making codes like Caesar ciphers.
This example shifts the letter ‘a’ along 5 places in the alphabet so it becomes ‘f’:
display.scroll(chr(ord('a') + 5))
The following example encodes the string ‘hello’ with an offset of 13. This kind of Caesar cipher is also known as ROT13. You can use the same code to encode and decode messages:
from microbit import *
plaintext = 'hello'
for letter in plaintext:
if ord(letter) > 109:
offset = -13
else:
offset = 13
display.scroll(chr(ord(letter) + offset))
Exercises¶
- Using this sentence , use string manipulation to make the first letter of every word capitalized.
"The quick brown fox jumps over the lazy dog near the bank of the river."
- Also, using the same sentence, change every instance of ‘a’ into an ‘o’.
- Using the original sentence in #1, count the number of words.
- For a give sentence below, check how many vowels are there and display it on the LED of the micro:bit.:
"Be not afraid of greatness. Some are born great,
some achieve greatness, and others have greatness thrust upon them."