5.7. Strings¶
5.7.1. Length of strings, string slices¶
Make a program strlast.py
that asks the user to enter her family name, and prints the last letter of the family name.
Question To select letters from a string, one has to use
Round brackets (
()
)Curley brackets (
{}
)Angle brackets (
<>
)Square brackets (
[]
)
Write a program strrange.py
that asks the user to enter her family name, and prints the 3rd, 4th and 5th letter of the name.
Question What index (on the string containing the family name) could be used for this?
2:5
3:5
4:6
-2:-5
5.7.2. String traversal (part 1)¶
In this exercise, you will create a program that prints your family name backwards. As a hint, first make a program with a while statement (save it as strback1.py
) that prints the following:
10 9 8 7 6 5 4 3 2 1 0
Question By default, a print statement prints a newline after printing the value. How can this be changed to a whitespace (instead of a newline)? By adding to the print statement:
end='\t'
, for instanceprint(i, end='\t')
end=' '
, for instanceprint(i, end=' ')
end=
, for instanceprint(i, end=)
With the knowledge gained from the exercise above, write a program that asks for your family name, and prints it backwards. Save it as strback2.py
.
Question You will need the number of letters in the family name. How can this be retrieved?
Using
len(..)
, which is in the string module.Using
length(..)
.Using another loop.
Using
len(..)
.
5.7.3. String traversal (part 2), string methods¶
Run this program:
# program that prints the result of a division
a = 2.0/8.0
print("The division directly printed: ", a)
It shows that decimals in floating points are printed using a dot (.). Although this is actually standard in English, some programs read and write decimals using a comma, i.e. 0,25 instead of 0.25.
As an exercise, modify the program given above, such that it prints the result of a division (i.e., the variable a) using a decimal comma. Convert a to a string, and use a string traversal encoded in a while statement (like you did in the previous exercise) to replace the dot with a comma. Save the program as strreplace1.py.
.
Question Almost certainly you need an if
statement inside the while
loop. How did you use it?
To stop the loop at the end of the string.
To select letters that are equal to a
.
.To rerun the loop in case a
.
is not found.
The previous exercise showed that it is quite a lot of work to manipulate strings. For this reason, Python comes with built-in methods on strings. These methods are called using dot notation, e.g. str.find('apple','a')
. Have a look at the description of the built-in str
methods in the Python documentation. Now, rewrite strreplace1.py
using the appropriate function from str
. Save the program as strreplace2.py
.
Question Which function did you use?
str.find(..)
str.replace(..)
str.partition(..)
str.split(..)