Skip to main content

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.

L1

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, like range.
  • 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" raises TypeError.
  • Methods like upper() return a new string; the original stays unchanged unless you reassign.
  • Concatenation a + b and repetition a * n also create new strings.
  • Immutability makes strings hashable (usable as dict keys / set items) 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 str methods). Call them as len(s), not s.len().
  • str(x) converts other types to text. ord / chr map characters ↔ Unicode code points.
FunctionWhat it doesExampleResult
len(s)Number of characterslen("Python")6
str(x)Convert value to stringstr(42)"42"
ord(ch)Unicode code point of one charord("A")65
chr(n)Character for code point nchr(65)"A"
ascii(s)Printable ASCII escape formascii("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 characterssorted("cab")["a", "b", "c"]
min(s) / max(s)Smallest / largest charactermin("Python")"P" (by code point)
any(ch.isdigit() for ch in s)Pattern with generator + built-inany(c.isdigit() for c in "a1")True

str methods — inspect and search

  • Call as s.method(...). Indexes are 0-based. Methods never change s — they return a new value.
  • find / rfind return -1 when missing; index / rindex raise ValueError.
MethodWhat it doesExample on "Python"Result
s.count(sub)How many non-overlapping matchess.count("t")1
s.find(sub) / s.rfind(sub)First / last index, or -1s.find("th")2
s.index(sub) / s.rindex(sub)First / last index, or errors.index("th")2
s.startswith(prefix)Prefix checks.startswith("Py")True
s.endswith(suffix)Suffix checks.endswith("on")True
sub in sMembership (operator)"tho" in sTrue
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 than lower() for Unicode).
MethodWhat it doesExampleResult
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) inserts sep between string parts — the iterable must yield strings.
  • join is the efficient way to build a big string from many pieces.
  • splitlines() splits on line boundaries and handles \n / \r\n.
MethodWhat it doesExampleResult
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 sepWhole 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 len take the string as an argument.
CategoryCommon APIsUse when
Built-inslen, str, ord, chr, formatLength, convert, code points
Inspect / testisalpha, isdigit, startswith, endswithValidate shape of text
Searchfind, index, count, inLocate or count substrings
Caselower, upper, title, casefoldNormalize for display / compare
Trim / padstrip, zfill, center, ljustClean input or align columns
Editreplace, removeprefix, removesuffixSubstitute or drop edges
Split / joinsplit, rsplit, join, partitionParse CSV-like text; rebuild
Formatf-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: \n newline, \t tab, \\ 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 in test substrings: "py" in "python" is True.
  • Comparisons are lexicographic by Unicode code points.
  • Normalize case with casefold() before case-insensitive compares.
  • ord("A") → 65, chr(65) → "A" for character codes.
NeedPrefer
Build from parts"".join(parts)
Insert valuesf-string
Find or -1find
Find or errorindex
Trim edgesstrip
L2

Advanced — Strings

Unicode and encoding basics

  • str holds Unicode text. bytes holds 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.
  • in on 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/replace is enough often.
words = ["learn", "code", "guru"]
print(" ".join(words).title())
# Output:
# Learn Code Guru

String vs bytes pitfalls

  • You cannot mix str and bytes with + without encoding/decoding.
  • Opening files in binary mode returns bytes lines; text mode returns str.
  • Network and crypto APIs often speak bytes; UI and most tutorials speak str.
  • b"abc"[0] is an int (97), not b"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.
L3

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.

L4

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
L5

Problem Solving Tricks

  • Use f-strings for formatting; keep .format and % for reading old code.
  • Prefer join over += 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 / endswith instead of fragile slices.
  • Empty string is falsy: if not s: catches blank input.
  • Sort characters with "".join(sorted(s)) for anagram checks.
  • strip before parsing user input — trailing newlines are common.
L6

Practice Programs List

  1. Reverse a string with slicing and print it.
  2. Check whether a string is a palindrome (ignore case).
  3. Count vowels and consonants in a sentence.
  4. Replace all spaces with hyphens without using replace (use split/join).
  5. Print character frequencies in alphabetical order of keys.
  6. Extract the domain from an email with partition("@") or split.
  7. Validate that a string is alphanumeric with isalnum.
  8. Format a receipt line with name left-aligned and price right-aligned.
  9. Remove leading zeros from a numeric string carefully ("000" → "0").
  10. Build an acronym from a multi-word title.
  11. Count words in a paragraph using split.
  12. Check if two strings are anagrams by sorting characters.