📘 CodingMarble Learn

Strings in Python

A string is an immutable sequence of characters written in single, double or triple quotes. Each character has a positive index (0 from the left) and a negative index (−1 from the right). Operations: + (concatenation), * (repetition), in / not in (membership) and slicing s[start:stop:step], which takes characters from start up to but not including stop. Traversal means visiting each character with a for or while loop. Built-in methods like len(), upper(), lower(), title(), capitalize(), count(), find(), index(), replace(), split(), join(), strip(), startswith(), endswith(), isalpha(), isdigit(), isalnum(), islower(), isupper() and isspace() return new values without changing the original string.

🎬 Step-by-step story

  1. A string is a row of letters. Each letter has a number called an index. It starts at 0 from the left and −1 from the right.
  2. Plus joins two strings. Star repeats a string. 'in' checks if a piece is inside.
  3. Slicing takes a part. s[1:4] takes places 1, 2 and 3, not 4. s[::-1] reads the string backwards.
  4. Traversal means visiting each letter with a loop. Here we count the vowels one by one.
  5. String methods like upper(), find() and replace() give a new answer. The old string stays the same.
  6. Your turn: type a word and a slice, and see which letters are picked.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Why does indexing start at 0?

The index tells how many steps from the start. The first letter is 0 steps away.

Why is 'Age' + 16 an error?

+ joins strings only. 16 is a number, so Python does not know what to do. Use 'Age' + str(16).

Why does s[1:4] stop at index 3?

The stop value is where the knife cuts, and that letter is not included. So 4 − 1 = 3 letters are taken.

for ch in s or for i in range(len(s))?

Use for ch in s when you only need the letters; use the index loop when you also need the position.

If upper() doesn't change s, where does the result go?

It returns a new string. Save it: s = s.upper(). The old string is left as it was.

Creating strings and indexing

A string is written in quotes: 'Hi', "Hi", or '''many lines'''. Strings are immutable: s[0] = 'J' gives a TypeError.

Indexing: s = 'PYTHON' → s[0] = 'P', s[5] = 'N', s[-1] = 'N', s[-6] = 'P'. An index outside the range gives IndexError. len(s) = 6.

String operations: concatenation, repetition, membership, slicing

Traversing a string

s = 'PYTHON'
for ch in s:              # by character
    print(ch, end=' ')

for i in range(len(s)):   # by index
    print(i, s[i])

i = 0
while i < len(s):         # with while
    print(s[i]); i += 1

Counting vowels: v = 0; for ch in s.lower(): if ch in 'aeiou': v += 1.

Built-in string functions and methods

MethodExample → result
len(s)len('cat') → 3
upper(), lower()'Hi'.upper() → 'HI'
title(), capitalize()'hello world'.title() → 'Hello World'; .capitalize() → 'Hello world'
count(sub)'banana'.count('a') → 3
find(sub) / index(sub)'banana'.find('n') → 2; find gives −1 if missing, index gives ValueError
replace(old, new)'cat'.replace('c', 'b') → 'bat'
split(sep), join(list)'a b c'.split() → ['a', 'b', 'c']; '-'.join(['a', 'b']) → 'a-b'
strip(), lstrip(), rstrip()' hi '.strip() → 'hi'
startswith(), endswith()'python'.startswith('py') → True
isalpha(), isdigit(), isalnum()'abc1'.isalnum() → True; '12'.isdigit() → True
islower(), isupper(), isspace()'ABC'.isupper() → True
partition(sep)'a=b'.partition('=') → ('a', '=', 'b')

None of these change s; they return a new value.

Board exam focus

Expect output questions on slicing and methods (1–2 marks) and programs: count vowels/uppercase/digits, check palindrome, reverse words, change case, replace characters (3 marks).

Key formulas and definitions

Worked examples

1. s = 'COMPUTER'. Find s[2], s[-2], s[2:5], s[::-2].

s[2] = 'M'; s[-2] = 'E'; s[2:5] = 'MPU'; s[::-2] = 'RTPO' (indexes 7, 5, 3, 1).

2. Output? print('ab' * 2 + 'c', 'b' in 'abc', len('Hi there'))

ababc True 8

3. Count uppercase letters, lowercase letters and digits in 'Class11A'.

u = l = d = 0 for ch in 'Class11A': if ch.isupper(): u += 1 elif ch.islower(): l += 1 elif ch.isdigit(): d += 1 # u = 2, l = 4, d = 2

4. Check whether a string is a palindrome.

s = input().lower() if s == s[::-1]: print('Palindrome') else: print('Not palindrome') # 'Madam' → Palindrome

5. Output? s = 'hello world'; print(s.title(), s.find('o'), s.count('l'), s.replace('l', 'L', 1))

Hello World 4 3 heLlo world

6. Change the case of each letter (swap) without swapcase().

r = '' for ch in s: if ch.isupper(): r += ch.lower() else: r += ch.upper() # 'PyThOn' → 'pYtHoN'

7. Print each word of a sentence on its own line and the number of words.

w = 'I love Python'.split() for x in w: print(x) print(len(w)) # 3

Common mistakes

Practice quiz

1. For s = 'PYTHON', s[-2] is:
2. 'ab' * 3 gives:
3. s[::-1] does what?
4. 'banana'.find('z') returns:
5. Which method splits a sentence into words?

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is string slicing in Python?

Taking a part of a string with s[start:stop:step], from start up to but not including stop.

Why are strings immutable?

A string object cannot be changed after it is made; any change creates a new string. This makes strings safe to share.

What is the difference between find() and index()?

Both give the first position of a substring; find() returns −1 if it is missing, index() raises a ValueError.

Where this is taught

RomaniaClasa a XI-aData structures
CBSE (India)Class 11Computational Thinking and Programming - 1
England (GCSE, A level)Year 103.2 Programming
USA (Common Core, NGSS, AP)Grade 11Using Objects and Methods
USA (Common Core, NGSS, AP)Grade 11Selection and Iteration
Russia8 классAlgorithms and programming
Russia8 классAlgorithms and programming
Russia10 классAlgorithms and programming

Learn first

Learn next

Related lessons

All Computer Science lessons