☰ Contents · Computing

Arithmetic practice and strings

Lessons 28–29 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
29

Working with strings in Python

Textbook: pp. 65–67
GoalKnows what a string is, joins strings with +, repeats them with *, finds the length with len(), and takes parts of a string with an index and a slice.
New words
string: a sequence of letters, digits, signs and spaces in quotes · satrlen(): the function that gives the number of characters in a string · len()index: the number of a character in a string; counting starts from 0 · indeksslice: part of a string, written a[start:end:step] · kesim
Explanation

A string is a sequence of characters in quotes; a space is also a character. Two strings can be joined with + (you put the space between them yourself), and * repeats a string a number of times: "Ha" * 3 gives HaHaHa. len(string) returns the number of characters. Every character in a string has a number, its index, which starts from 0: in "TOSHKENT" the index of T is 0 and of O is 1. a[i] is one character, a[start:end] is the part from start to end but without the character at end; a[:end] goes from the beginning, a[start:] to the end, and a[start:end:step] takes characters with a step. A string cannot be changed in place: a new string is made and the old one stays as it was. Many mistakes come from forgetting that the end character is not included.

Worked examples
Joining and length: a = "Yangi" ⏎ b = "yil" ⏎ c = a + " " + b ⏎ print(c, len(c)) The screen shows Yangi yil 9 (5 + 1 + 3 = 9 characters).
Index and slices: s = "TOSHKENT" ⏎ print(s[0], s[2:5], s[:3], s[4:], s[1:8:3]) The result is T SHK TOS KENT OKT. Here s[1:8:3] takes the characters with indexes 1, 4, 7 (O, K, T).
Class activity

“String surgeon”: each pair writes the name of its city (for example SAMARQAND) with the indexes numbered under it, then the partner finds the result of a slice (for example [3:6]) by hand first and checks it in IDLE.

Practice
1
What is len("kitob" + "xona") equal to?
2
If s = "SAMARQAND", what does s[3:6] give?
3
Write a program that prints the word "Ha" 5 times in one line.
4
Why is it handy to imagine that indexes start from 0?