Working with strings in Python
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.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| character | T | O | S | H | K | E | N | T |
A website editor put only the first three letters of a long name in a headline. Slicing text and counting its length made this quick. The headline looked tidy.
Editors, programmers and data workers slice text, measure its length and take the part they need.
Count the characters in a short slogan, including spaces, and decide whether it would fit on a name tag of 20 characters. Do it on paper.
1a = "Yangi" 2b = "yil" 3c = a + " " + b 4print(c, len(c))
Yangi yil 9
1s = "TOSHKENT" 2print(s[0], s[2:5], s[:3], s[4:], s[1:8:3])
T SHK TOS KENT OKT
“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.