Python Basics
Strings
Indexing and negative indexes, slicing, immutability, the most useful string methods, searching, splitting and joining, and classic string programs.
A string is an immutable sequence of characters. Single, double or triple quotes all work.
Python
s = "Kalvium"
print(len(s), s[0], s[-1], s[2]) # negative indexes count from the end
print(s[0:3], s[3:], s[:4], s[-3:]) # slices: start included, end excluded
print(s[::-1]) # step -1 reverses
print(s[::2]) # every second characterOutput
7 K m l Kal vium Kalv ium muivlaK Klim
s[1:4] is "alv".Strings are immutable
You cannot change a character in place; build a new string instead:
Python
s = "python"
# s[0] = "P" # TypeError: 'str' object does not support item assignment
s = "P" + s[1:]
print(s)Output
Python
Essential string methods
| Method | Does | Example result |
|---|---|---|
upper(), lower(), title(), capitalize() |
change case | "hi there".title() → Hi There |
strip(), lstrip(), rstrip() |
remove whitespace (or given characters) | " hi ".strip() → hi |
split(sep) |
split into a list | "a,b,c".split(",") → ['a', 'b', 'c'] |
sep.join(list) |
join a list into a string | "-".join(["a","b"]) → a-b |
replace(old, new) |
replace all occurrences | "aaa".replace("a","b") → bbb |
find(sub) / index(sub) |
position of sub (find gives −1 if missing) |
"hello".find("l") → 2 |
count(sub) |
occurrences | "banana".count("a") → 3 |
startswith, endswith |
prefix / suffix tests | |
isdigit, isalpha, isalnum, isspace, isupper |
character class tests |
Python
email = " Asha.Rao@Example.COM "
clean = email.strip().lower()
user, domain = clean.split("@")
print(clean, user, domain)
print(clean.endswith(".com"), clean.count("a"), clean.find("rao"))
words = "data structures and algorithms".split()
print(words)
print(" ".join(w.capitalize() for w in words))
print("-".join(["2026", "11", "14"]))Output
asha.rao@example.com asha.rao example.com True 4 5 ['data', 'structures', 'and', 'algorithms'] Data Structures And Algorithms 2026-11-14
Looping over strings
Python
text = "Hello, World 2026!"
letters = digits = spaces = others = 0
for ch in text:
if ch.isalpha():
letters += 1
elif ch.isdigit():
digits += 1
elif ch.isspace():
spaces += 1
else:
others += 1
print(letters, digits, spaces, others)
for i, ch in enumerate("abc"):
print(i, ch, ord(ch)) # ord gives the Unicode code; chr goes back
print(chr(65), chr(0x20B9))Output
10 4 2 2 0 a 97 1 b 98 2 c 99 A ₹
Classic string programs
Python
def is_palindrome(s):
cleaned = "".join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]
def count_vowels(s):
return sum(1 for c in s.lower() if c in "aeiou")
def is_anagram(a, b):
return sorted(a.replace(" ", "").lower()) == sorted(b.replace(" ", "").lower())
def char_frequency(s):
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
return freq
print(is_palindrome("A man, a plan, a canal: Panama"))
print(count_vowels("Object Oriented Programming"))
print(is_anagram("Listen", "Silent"), is_anagram("Dormitory", "Dirty room"))
print(char_frequency("mississippi"))Output
True
9
True True
{'m': 1, 'i': 4, 's': 4, 'p': 2}Test yourself
4 questions · pick an answer to check it instantly
- 1
For
s = "programming", what iss[3:7]?Slicing includes the start and excludes the end: characters at 3–6 are g, r, a, m. - 2
What does
"banana".find("z")return?findreturns −1 when the substring is missing;indexwould raiseValueError. - 3
What does
" | ".join(["C", "C++", "Python"])produce?joinplaces the separator between the list elements. - 4
Why does
s[0] = "X"fail for a strings?Strings cannot be modified in place; create a new string.