Strings & Data Structures
Strings
Complete lesson for Strings using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Strings
Section: Strings & Data Structures. Python strings: creation, indexing, slicing, immutability, methods, formatting, and common string algorithms.
What is a string?
- A string (
str) is an immutable sequence of Unicode characters. - Create with single quotes, double quotes, or triple quotes for multi-line text.
len(s)is the number of characters. Empty string is"".- Real life: names, emails, file paths, messages, and JSON text are all strings.
s = "Python"
print(type(s).__name__, len(s))
# Output:
# str 6 Indexing and slicing
- Indexes start at 0.
s[0]is the first character;s[-1]is the last. - Slicing
s[start:stop:step]— stop is exclusive, likerange. s[::-1]reverses a string.s[:3]is a prefix;s[-3:]is a suffix.- Out-of-range index raises
IndexError; out-of-range slice quietly clamps.
s = "Python"
print(s[0], s[-1], s[1:4], s[::-1])
# Output:
# P n yth nohtyP Immutability
- You cannot change a character in place:
s[0] = "x"raisesTypeError. - Methods like
upper()return a new string; the original stays unchanged unless you reassign. - Concatenation
a + band repetitiona * nalso create new strings. - Immutability makes strings hashable (usable as
dictkeys /setitems) when content is fixed.
s = "hi"
t = s.upper()
print(s, t)
# Output:
# hi HI Built-in functions that work on strings
- These are **built-in functions** (not
strmethods). Call them aslen(s), nots.len(). str(x)converts other types to text.ord/chrmap characters ↔ Unicode code points.
| Function | What it does | Example | Result |
|---|---|---|---|
len(s) | Number of characters | len("Python") | 6 |
str(x) | Convert value to string | str(42) | "42" |
ord(ch) | Unicode code point of one char | ord("A") | 65 |
chr(n) | Character for code point n | chr(65) | "A" |
ascii(s) | Printable ASCII escape form | ascii("hi") | Same idea as repr for ASCII text |
repr(s) | Developer representation (shows quotes/escapes) | repr("hi") | 'hi' |
format(value, spec) | Format a value (also used by f-strings) | format(3.14159, ".2f") | "3.14" |
sorted(s) | Sorted list of characters | sorted("cab") | ["a", "b", "c"] |
min(s) / max(s) | Smallest / largest character | min("Python") | "P" (by code point) |
any(ch.isdigit() for ch in s) | Pattern with generator + built-in | any(c.isdigit() for c in "a1") | True |
str methods — inspect and search
- Call as
s.method(...). Indexes are 0-based. Methods never changes— they return a new value. find/rfindreturn-1when missing;index/rindexraiseValueError.
| Method | What it does | Example on "Python" | Result |
|---|---|---|---|
s.count(sub) | How many non-overlapping matches | s.count("t") | 1 |
s.find(sub) / s.rfind(sub) | First / last index, or -1 | s.find("th") | 2 |
s.index(sub) / s.rindex(sub) | First / last index, or error | s.index("th") | 2 |
s.startswith(prefix) | Prefix check | s.startswith("Py") | True |
s.endswith(suffix) | Suffix check | s.endswith("on") | True |
sub in s | Membership (operator) | "tho" in s | True |
s.isalpha() | All alphabetic and non-empty | "Python".isalpha() | True |
s.isdigit() | All digits and non-empty | "123".isdigit() | True |
s.isalnum() | All alphanumeric and non-empty | "Py3".isalnum() | True |
s.isspace() | All whitespace and non-empty | " \t".isspace() | True |
s.isupper() / s.islower() | Case tests | "PYTHON".isupper() | True |
s.istitle() | Title-cased words | "Hello World".istitle() | True |
s.isidentifier() | Valid Python identifier? | "score1".isidentifier() | True |
s.isprintable() | All printable (or empty) | "hi".isprintable() | True |
s.isdecimal() / s.isnumeric() | Numeric character tests | "½".isnumeric() | True |
str methods — transform and case
- Every “change” returns a **new**
str. Rebind if you need to keep it:s = s.strip(). casefold()is a stronger lowercase for caseless matching (better thanlower()for Unicode).
| Method | What it does | Example | Result |
|---|---|---|---|
s.lower() / s.upper() | Lower / upper case copy | "Py".upper() | "PY" |
s.capitalize() | First char upper, rest lower | "pYTHON".capitalize() | "Python" |
s.title() | Capitalize each word | "learn code".title() | "Learn Code" |
s.swapcase() | Swap upper ↔ lower | "PyThOn".swapcase() | "pYtHoN" |
s.casefold() | Aggressive lower for compares | "Straße".casefold() | "ss" |
s.strip() / lstrip() / rstrip() | Trim edges (default: whitespace) | " hi ".strip() | "hi" |
s.removeprefix(p) / removesuffix(p) | Drop prefix/suffix if present (3.9+) | "TestX".removesuffix("X") | "Test" |
s.replace(old, new[, count]) | Replace substring(s) | "aa".replace("a", "b") | "bb" |
s.center(w[, fill]) | Center in width w | "hi".center(6, "-") | "--hi--" |
s.ljust(w) / s.rjust(w) | Left / right justify | "hi".rjust(5, "0") | "000hi" |
s.zfill(w) | Pad with zeros on the left | "42".zfill(5) | "00042" |
s.expandtabs([tabsize]) | Turn tabs into spaces | "a\tb".expandtabs(4) | "a b" |
s.encode(encoding) | str → bytes | "hi".encode("utf-8") | b"hi" |
s = " Hello World "
print(s.strip())
print(s.strip().replace("World", "Python"))
# Output:
# Hello World
# Hello Python str methods — split, join, and partition
s.split()splits on whitespace and discards empty pieces.s.split(",")uses a delimiter.sep.join(iterable)insertssepbetween string parts — the iterable must yield strings.joinis the efficient way to build a big string from many pieces.splitlines()splits on line boundaries and handles\n/\r\n.
| Method | What it does | Example | Result |
|---|---|---|---|
s.split([sep[, maxsplit]]) | Split into list of pieces | "a,b,c".split(",") | ["a", "b", "c"] |
s.rsplit([sep[, maxsplit]]) | Split from the right | "a,b,c".rsplit(",", 1) | ["a,b", "c"] |
s.splitlines() | Split on line breaks | "a\nb".splitlines() | ["a", "b"] |
sep.join(iterable) | Join string pieces with sep | "-".join(["a","b"]) | "a-b" |
s.partition(sep) | 3-tuple: before, sep, after | "a-b-c".partition("-") | ("a", "-", "b-c") |
s.rpartition(sep) | Partition from the right | "a-b-c".rpartition("-") | ("a-b", "-", "c") |
s.partition missing sep | Whole string, then empty parts | "abc".partition("-") | ("abc", "", "") |
parts = "a,b,c".split(",")
print(parts)
print("-".join(parts))
# Output:
# ['a', 'b', 'c']
# a-b-c str methods — overview cheat sheet
- Use this map to pick the right tool quickly; the tables above have examples.
- Remember: methods return new strings; built-ins like
lentake the string as an argument.
| Category | Common APIs | Use when |
|---|---|---|
| Built-ins | len, str, ord, chr, format | Length, convert, code points |
| Inspect / test | isalpha, isdigit, startswith, endswith | Validate shape of text |
| Search | find, index, count, in | Locate or count substrings |
| Case | lower, upper, title, casefold | Normalize for display / compare |
| Trim / pad | strip, zfill, center, ljust | Clean input or align columns |
| Edit | replace, removeprefix, removesuffix | Substitute or drop edges |
| Split / join | split, rsplit, join, partition | Parse CSV-like text; rebuild |
| Format | f-strings, str.format, % | Insert values into templates |
Formatting strings
- f-strings (Python 3.6+):
f"hi {name}"— preferred for readability. str.format:"hi {}".format(name)still common in older code.- Old
%formatting:"hi %s" % name— know it for reading legacy code. - Format specs:
f"{pi:.2f}",f"{n:04d}",f"{s:>10}"for width/align.
name = "Ada"
score = 95.5
print(f"{name} scored {score:.1f}")
# Output:
# Ada scored 95.5 Escape sequences and raw strings
- Common escapes:
\nnewline,\ttab,\\backslash,\'/\"quotes. - Raw strings
r"C:\path"treat backslashes literally — handy for paths and regex. - Triple-quoted strings keep real newlines without
\n. - Adjacent string literals concatenate at compile time:
"py" "thon"→"python".
Membership and comparison
in/not intest substrings:"py" in "python"isTrue.- Comparisons are lexicographic by Unicode code points.
- Normalize case with
casefold()before case-insensitive compares. ord("A")→ 65,chr(65)→"A"for character codes.
| Need | Prefer |
|---|---|
| Build from parts | "".join(parts) |
| Insert values | f-string |
| Find or -1 | find |
| Find or error | index |
| Trim edges | strip |
Advanced — Strings
Unicode and encoding basics
strholds Unicode text.bytesholds raw bytes. Encode/decode between them:s.encode("utf-8"),b.decode("utf-8").- Default source encoding is UTF-8. File I/O should set
encoding="utf-8"explicitly on Windows. - Normalization (
unicodedata.normalize) matters when comparing accented text. - Length is characters, not bytes —
"é"may be one or two code points depending on composition.
Performance habits
- Never build huge strings with
+=in a hot loop; use a list +join. inon a long string is a substring search (not hash lookup).- Prefer methods (
startswith) over slicing when intent is clearer. - Compile regex only when patterns are complex; simple
find/replaceis enough often.
words = ["learn", "code", "guru"]
print(" ".join(words).title())
# Output:
# Learn Code Guru String vs bytes pitfalls
- You cannot mix
strandbyteswith+without encoding/decoding. - Opening files in binary mode returns
byteslines; text mode returnsstr. - Network and crypto APIs often speak
bytes; UI and most tutorials speakstr. b"abc"[0]is anint(97), notb"a"— a classic gotcha.
Interview string patterns
- Palindrome: compare
s == s[::-1]after normalizing case/spaces if required. - Anagram: sort both strings or count characters with a dict /
Counter. - Frequency map: loop characters and tally; or use
collections.Counter. - Two-pointer scans on a string often beat nested O(n²) searches.
Tricky Interview Points
Q1) Are Python strings mutable?
Answer No. Strings are immutable. Methods return new strings; you rebind the name if you want to keep the result.
Q2) What is the difference between find and index?
Answer find returns -1 when the substring is missing. index raises ValueError.
Q3) How do you reverse a string?
Answer Slicing s[::-1] is the usual way. "".join(reversed(s)) also works.
Q4) What does strip remove by default?
Answer Leading and trailing whitespace (spaces, tabs, newlines). Pass a string of chars to strip those instead.
Q5) Why use join instead of + in a loop?
Answer Repeated + builds many temporary strings (quadratic cost). join builds once efficiently.
Q6) What is an f-string?
Answer A formatted string literal prefixed with f/F that embeds expressions in braces, evaluated at runtime.
Q7) How is string slicing different from indexing on bad bounds?
Answer Bad index → IndexError. Bad slice bounds are clamped; you may get a shorter or empty string.
Q8) Is "a" "b" valid?
Answer Yes — adjacent literals concatenate to "ab" at compile time.
Q9) How do you check a substring?
Answer Use sub in s, or s.find(sub) != -1, or s.startswith / endswith for edges.
Q10) What is the difference between str and bytes?
Answer str is text (Unicode). bytes is raw binary data. Convert with encode/decode.
Q11) How do split and rsplit differ?
Answer Both split on a separator; rsplit splits from the right. Useful with maxsplit when only the last field should stay whole.
Q12) Are strings hashable?
Answer Yes, because they are immutable. They can be dict keys and set elements.
Simple Programs
Reverse a string
s = "Python"
print(s[::-1])
# Output:
# nohtyP Palindrome check
s = "level"
print(s == s[::-1])
# Output:
# True Count vowels
s = "Education"
vowels = "aeiouAEIOU"
count = 0
for ch in s:
if ch in vowels:
count += 1
print(count)
# Output:
# 5 split and join
line = "learn code guru"
words = line.split()
print(words)
print("-".join(words))
# Output:
# ['learn', 'code', 'guru']
# learn-code-guru Character frequency
s = "banana"
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
for ch in sorted(freq):
print(ch, freq[ch])
# Output:
# a 3
# b 1
# n 2 Title-case words with join
s = "python string methods"
print(" ".join(w.capitalize() for w in s.split()))
# Output:
# Python String Methods Problem Solving Tricks
- Use f-strings for formatting; keep
.formatand%for reading old code. - Prefer
joinover+=when building strings in loops. s[::-1]reverses;s[::2]takes every second character.find→ -1,index→ error — pick based on whether missing is normal.- Normalize with
casefold()for case-insensitive compares. - Raw strings
r"..."help Windows paths and regex patterns. - Test edges with
startswith/endswithinstead of fragile slices. - Empty string is falsy:
if not s:catches blank input. - Sort characters with
"".join(sorted(s))for anagram checks. stripbefore parsing user input — trailing newlines are common.
Practice Programs List
- Reverse a string with slicing and print it.
- Check whether a string is a palindrome (ignore case).
- Count vowels and consonants in a sentence.
- Replace all spaces with hyphens without using
replace(use split/join). - Print character frequencies in alphabetical order of keys.
- Extract the domain from an email with
partition("@")orsplit. - Validate that a string is alphanumeric with
isalnum. - Format a receipt line with name left-aligned and price right-aligned.
- Remove leading zeros from a numeric string carefully (
"000"→"0"). - Build an acronym from a multi-word title.
- Count words in a paragraph using
split. - Check if two strings are anagrams by sorting characters.