Skip to content
Educora
IntermediateGrade 925 min34 / 59

Strings and string operations

Indexes (negative ones too), slices and `[::-1]`; `len`, `+`, `*`, `in`, `count`, `find`, `replace`, `upper`, `isdigit`, `split`, `join`; loops over characters, digits through `str(n)` and the string patterns of the DİM written tasks.

Check yourself
In this lesson you will learn
  • work with indexes (negative ones too) and slices, including [::-1]
  • predict the results of len, +, *, in and of the methods count, find, replace, upper, lower, isdigit, split, join
  • loop over characters and build new strings: distinct characters, filters, neighbouring characters
  • process items given on one line with split(' ') and work with digits through str(n)

'Bakı 2026' is a string of 9 characters: 4 letters, 1 space and 4 digits. To Python a string is a chain of numbered characters: you can take any character by its number, cut out a part, count characters and turn the string around. In both 2025 DİM papers one of the written programs was about strings (the number of distinct characters; processing items typed on one line and separated by spaces), and in 2026 string operations appeared inside the list and function tasks. This lesson continues input() and the str type from «Programming languages and Python: variables, input and output».

Strings, indexes and slices

Definition
String (str)

A sequence of characters written between quotes: 'data', "3ab6", '' (the empty string). input() always returns what was typed as a string; if a number is needed, write int(input()).

Definition
Index

The position number of a character in a string. From the left it starts at 0: the first character is s[0], the last is s[len(s) - 1]. From the right you count with negative indexes: s[-1] is the last character, s[-2] the second to last.

s = 'PYTHON'PYTHON
index012345
negative index−6−5−4−3−2−1
Every character has two numbers: s[1] and s[-5] are the same character, 'Y'.
s[i] s[-1] = s[len(s) - 1]
where:
  • s[i]the character with index i (itself a string)
  • len(s)the number of characters; the last index is len(s) − 1

s[len(s)] gives an error (IndexError): there is no such index.

s[a:b:c]
where:
  • athe start index (included); if omitted — from the beginning
  • bthe end index (not included); if omitted — to the end
  • cthe step; 1 if omitted; a negative step goes from right to left

A slice runs from a to b − 1 with step c. s[::-1] is the reversed string; with c = 1 a slice has b − a characters.

Python
s = 'programming'
print(len(s), s[0], s[-1], s[3])
print(s[3:7], s[:3], s[7:])
print(s[::2], s[::-1])
print(s[-4:], s[1:8:3])
▸ Expected output
11 p g g
gram pro ming
pormig gnimmargorp
ming rrm
Work out each line yourself first: 'programming' has 11 characters, indexes 0…10.
Example 1. Indexes and slices

For s = 'informatics' find: 1) s[2:6]; 2) s[-3:]; 3) s[1::3]; 4) s[5] + s[0]; 5) s[::-1][:4].

Show solution
Indexes: i0 n1 f2 o3 r4 m5 a6 t7 i8 c9 s10 (len = 11).
1) 2, 3, 4, 5 → 'form' (6 is not included).
2) the last three characters → 'ics'.
3) 1, 4, 7, 10 → 'nrts'.
4) 'm' + 'i' → 'mi' (+ joins strings).
5) the reversed string is 'scitamrofni', its first four characters → 'scit'.

Operations and methods

Operations on a string return a new string or a number, and the original string does not change: strings are immutable, so s[0] = 'P' gives an error. If you need a change, build a new string and assign it again: s = s.upper().

OperationWhat it doesExampleResult
len(s)the number of characterslen('banana')6
+, *joining, repeating'ab' + 'c', 'ab' * 3'abc', 'ababab'
inis it a substring'nan' in 'banana'True
s.count(x)how many times x occurs (without overlaps)'banana'.count('a'), 'banana'.count('ana')3, 1
s.find(x)the first index, or −1 if absent'banana'.find('n'), 'banana'.find('z')2, -1
s.index(x)like find, but an error if x is absent'banana'.index('a')1
s.replace(a, b)replaces every a with b'banana'.replace('a', 'o')'bonono'
s.upper(), s.lower()upper / lower case'Baku'.upper()'BAKU'
s.isdigit()is it made only of digits'2026'.isdigit(), '20a'.isdigit()True, False
s.split(x)splits into a list at every x'3 ab 45'.split(' ')['3', 'ab', '45']
x.join(a)joins the items of a list with x'-'.join(['a', 'b'])'a-b'
The main string operations. split and join work with lists — see «Lists and list operations».
Python
s = 'banana'
print(s.count('a'), s.count('ana'), s.find('n'), s.find('z'))
print(s.replace('a', 'o'), s.upper(), 'nan' in s)
print('2026'.isdigit(), '20a'.isdigit())
print('ab' * 3 + '!', len(s * 2))
▸ Expected output
3 1 2 -1
bonono BANANA True
True False
ababab! 12
s.replace and s.upper return new strings; s itself stays 'banana'.

Capital and small letters are different characters: 'A' == 'a' is false. To count a letter regardless of case, first turn the string into small letters: s.lower().count('a'). upper() and lower() leave digits and signs unchanged.

Python
s = 'abracadabra'
k = s.count('a') + s.find('c')
t = s[k:] + s[:2]
print(t)
▸ Expected output
raab
The program of Example 2: find the result yourself first.
Example 2. A DİM-style task: methods and slices

Determine the output of the program above.
A) braab B) raab C) raba D) abra E) ra

Show solution
Indexes: a0 b1 r2 a3 c4 a5 d6 a7 b8 r9 a10.
s.count('a') = 5 (at indexes 0, 3, 5, 7, 10), s.find('c') = 4, so k = 9.
s[9:] = 'ra', s[:2] = 'ab', t = 'ra' + 'ab' = 'raab'. Answer: B.

Looping over characters and building a new string

A string can be walked in two ways: over the characters themselves (for c in s:) and over the indexes (for i in range(len(s)):). The second is chosen when you need the position or neighbouring characters (s[i] and s[i + 1]). A new string starts empty (k = '') and grows with k = k + c; k = c + k collects the characters in reverse order.

  1. 1
    An empty string

    k = '' — the characters already seen will be collected here.

  2. 2
    Loop

    for c in s: — look at every character.

  3. 3
    Is it new?

    if k.count(c) == 0: (or if c not in k:) — add only a character that is not there yet, with k = k + c.

  4. 4
    Result

    print(len(k)) — the number of distinct characters. A space is a character too.

Python
s = 'mississippi-2026'
v = 0
d = ''
k = ''
for c in s:
    if c in 'aeiou':
        v = v + 1
    if c.isdigit():
        d = d + c
    if k.count(c) == 0:
        k = k + c
print(v, d, k, len(k))
▸ Expected output
4 2026 misp-206 8
Three jobs in one loop: the number of vowels (4), a string made of the digits only ('2026') and the distinct characters ('misp-206', 8 characters).
Example 3. Neighbouring characters

Build a loop that counts the pairs of equal neighbouring characters in s = 'bookkeeper'. Why must it be range(len(s) - 1) and not range(len(s))?

Show solution
for i in range(len(s) - 1): and if s[i] == s[i + 1]: c = c + 1.
Indexes: b0 o1 o2 k3 k4 e5 e6 p7 e8 r9. Pairs: oo (1–2), kk (3–4), ee (5–6) — the answer is 3.
With range(len(s)) the last step has i = 9, and s[10] does not exist — an IndexError.
Python
s = 'olympiad'
k = ''
for i in range(len(s)):
    if i % 2 == 0:
        k = k + s[i].upper()
    elif s[i] in 'aeiou':
        k = k + '*'
    else:
        k = k + s[i]
print(k, len(k))
▸ Expected output
OlYmP*Ad 8
The program of Example 4: find the result yourself first.
Example 4. A DİM-style task: a loop over indexes

Determine the output of the program above.
A) oLyMpIaD 8 B) OlYmPiAd 8 C) OLYMPIAD 8 D) OlYmP*Ad 8 E) *lYmP**d 8

Show solution
Indexes: o0 l1 y2 m3 p4 i5 a6 d7.
Characters at even indexes (0, 2, 4, 6) become capitals: O, Y, P, A. When the first condition is true, elif is not checked, so a6 also becomes 'A', not a star.
At odd indexes: l1 — a consonant, stays; m3 — stays; i5 — a vowel → *; d7 — stays.
k = 'OlYmP*Ad', length 8. Answer: D. Trap: option E swaps the order of the conditions — if the vowel check came first, o0 and a6 would become stars too.

Numbers and strings: str(n) and int(s)

str(n) turns a number into a string of digits, and int(s) turns a string of digits into a number. This is the second way of working with digits (the first is n % 10 and n // 10, see «Working with numbers: digits, divisors and primes»): len(str(n)) is the number of digits, str(n)[::-1] the reversed notation, str(n).count('7') how many times the digit 7 occurs.

Python
n = 40718
t = str(n)
print(len(t), t[0], t[-1], t.count('0'))
print(int(t[::-1]), t == t[::-1])
s = 0
for c in t:
    s = s + int(c)
print(s, t + '5', n + 5)
▸ Expected output
5 4 8 1
81704 False
20 407185 40723
t + '5' joins strings ('407185'), while n + 5 adds numbers (40723).
Python
a = [707, 17, 1234, 77, 470, 5]
m = 0
for x in a:
    t = str(x)
    if t.count('7') == 1:
        m = m + x
    else:
        m = m - x
print(m)
▸ Expected output
-1536
The program of Example 5.
Example 5. A DİM-style task: str and count

Determine the output of the program above.
A) 1536 B) 487 C) −1536 D) −1459 E) −2006

Show solution
Numbers with exactly one digit 7 are added, the others are subtracted:
707 — twice → −707; 17 — once → +17; 1234 — none → −1234; 77 — twice → −77; 470 — once → +470; 5 → −5.
m = −707 + 17 − 1234 − 77 + 470 − 5 = −1536. Answer: C.

split and join: items given on one line

In written tasks the items are often typed on one line, separated by spaces: b = input(), then a = b.split(' '). The result is a list of strings: the first character of item i is a[i][0], the last is a[i][-1] (or a[i][len(a[i]) - 1]), its length is len(a[i]); if it is needed as a number, write int(a[i]). If a sum of indexes is asked, loop over the indexes.

Python
b = 'ada 7x7 radar 45 noon ab'
a = b.split(' ')
k = 0
s = 0
for i in range(len(a)):
    if a[i][0] == a[i][-1]:
        k = k + 1
        s = s + i
print(a)
print(k, s)
print('-'.join(a[:3]))
▸ Expected output
['ada', '7x7', 'radar', '45', 'noon', 'ab']
4 7
ada-7x7-radar
Items whose first and last characters are equal: 4 of them, the sum of their indexes 0 + 1 + 2 + 4 = 7. In the exam the first line is b = input().
Example 6. Numbers from a line

The line 10 205 3 4400 17 is typed on the keyboard. Find how many items end with the digit 0, their sum (as numbers) and the sum of their indexes.

Show solution
a = ['10', '205', '3', '4400', '17']. Condition: a[i][-1] == '0'.
i = 0: '10' — fits; i = 3: '4400' — fits; the others end in 5, 3, 7.
Count: 2; sum: int('10') + int('4400') = 4410; sum of indexes: 0 + 3 = 3.
Careful: '10' + '4400' would give the string '104400'.
Exercise

Print, on one line separated by a space, the number of distinct characters in s = 'informatics' and the string made of these characters in order of first appearance.

Exercise · Python
s = 'informatics'
k = ''
# collect the distinct characters in k

print(len(k), k)
▸ Expected output
10 informatcs
Exercise

In line = '31 405 7 1234 56 800', print the sum of the numbers whose first digit is greater than their last digit.

Exercise · Python
line = '31 405 7 1234 56 800'
a = line.split(' ')
total = 0
# loop over a here

print(total)
▸ Expected output
831

Key points

  • Indexes start at 0 from the left and at −1 from the right; in the slice s[a:b:c] b is not included, and s[::-1] reverses the string.
  • Strings are immutable: methods return new strings, so the result is assigned again, as in s = s.upper().
  • count counts (without overlaps), find searches (−1 if not found), replace replaces, isdigit checks for digits.
  • Distinct characters: k = '', for c in s:, if k.count(c) == 0: k = k + c, and len(k) at the end.
  • b.split(' ') gives a list of strings: a[i][0], a[i][-1], int(a[i]); str(n) and int(s) are the bridge between numbers and strings.

Check yourself

12 questions. Every correct answer earns XP.

1 / 12
What is s[-1] for s = 'python'?