Skip to main content

Learning outcomes

By the end of this chapter, you should be able to:
  • use important string methods
  • split and join text data
  • format output cleanly
  • solve basic string problems

30-minute recording plan

  • 0-8 min: core string methods
  • 8-13 min: find() and count() traps
  • 13-20 min: split() and join() usage
  • 20-25 min: string formatting patterns
  • 25-30 min: pattern questions (palindrome/frequency)

Common string methods

s = "  PyThOn  "
print(s.lower())
print(s.upper())
print(s.strip())
text = "banana"
print(text.count("a"))
print(text.find("na"))
print(text.replace("na", "NA"))
Method intent:
  • lower()/upper() for normalization
  • strip() for cleaning extra spaces
  • count() for frequency checks
  • find() for position lookup (-1 if missing)
  • replace() for controlled substitution

Beginner alert: find() trap

find() returns index, not True/False.
text = "python"
print(text.find("py"))  # 0
print(text.find("zz"))  # -1
So avoid this style:
# if text.find("py"):  # Wrong logic when index is 0
Use this instead:
if "py" in text:
    print("Found")

Split and join

line = "red,green,blue"
colors = line.split(",")
print(colors)

joined = "-".join(colors)
print(joined)
split() is useful for parsing input data.
join() is useful for rebuilding text in a chosen format.
split(",") splits only on commas. If you write split() with no argument, it splits on spaces/tabs/newlines.

Method chaining: return type tracker (MCQ-critical)

Always read chained expressions left to right and track type after each step. Common string method return types:
  • returns str: lower(), upper(), strip(), replace(old, new), join(iterable)
  • returns list: split()
  • returns bool: startswith(prefix), endswith(suffix), isalpha()
  • returns int: find(sub), index(sub) (but index raises error if missing)

Solved type/exceptions set (Q11-Q18 style)

  1. s[:3].upper().split() -> list
  2. s.startswith() -> raises TypeError (missing required prefix)
  3. s.startswith("hello") -> bool
  4. s.lowercase().isalpha() -> raises AttributeError (lowercase does not exist; correct is lower)
  5. s.isalpha().upper() -> raises AttributeError (isalpha() returns bool, and bool has no upper)
  6. s.replace('h').index("3") -> raises TypeError (replace needs old and new)
  7. s.join(s.split('-')) -> str
  8. s.join(s[0], s[1], s[3]) -> raises TypeError (join expects one iterable argument)
Note for 8:
  • if s is shorter than 4 characters, s[3] can raise IndexError before join runs.

Two high-frequency traps

  • Calling a method with missing required parameters causes TypeError.
  • Using a wrong method name (like lowercase) causes AttributeError.

String formatting

name = "Dhruv"
score = 92
print(f"{name} scored {score}")
print("{} scored {}".format(name, score))
Prefer f-strings for modern, readable output.

Format specifier mini-guide (MCQ-critical)

In an f-string, this form is very common:
  • f"{value:06}"
Meaning:
  • total width = 6
  • pad with leading zeros if needed
Example:
print(f"{500:06}")  # "000500"
print(f"{500:03}")  # "500" (already width 3)
Width/alignment symbols often asked in MCQs:
  • :<9 left align in width 9
  • :>9 right align in width 9
  • :^9 center align in width 9
  • :9 for strings behaves like left align by default

Solved exam-style case

a, b = "56"
s = f'{a*3:9}|{b*5:^9}|{a*7:>9}'
print(s)
Step:
  • a*3 -> "555" then :9 -> "555 "
  • b*5 -> "66666" then :^9 -> " 66666 "
  • a*7 -> "5555555" then :>9 -> " 5555555"
Final value:
'555      |  66666  |  5555555'

Quiz trap: strings equal to "000500"

print(f"{500:06}")      # "000500"   True
print(f"{500:03}")      # "500"      False
print("0"*3 + "500")    # "000500"   True
Common wrong options:
# "0"*3 + 500    # TypeError (str + int)
# 0*3 + "500"    # TypeError (int + str)

Basic pattern problems

Palindrome check

s = input("Enter string: ")
if s == s[::-1]:
    print("Palindrome")
else:
    print("Not palindrome")

Frequency of characters

s = "mississippi"
for ch in sorted(set(s)):
    print(ch, s.count(ch))

Code-trace trap: condition is narrower than it looks

word = input()
valid = False

if 'a' <= word[0] <= 'z':
    if word[0] == word[-1]:
        valid = True

print(valid)
Important reading:
  • it checks only first character is lowercase
  • it checks first and last characters are equal
  • it does not check every character is lowercase
Sample classification:
  • tacit -> True
  • trumpet -> True
  • ease -> True
  • TrumpeT -> False (first char uppercase)
Edge case:
  • empty input can raise IndexError at word[0]

Mini showcase: parse a CSV-style score line

row = "Aarav,Math,88"
name, subject, marks = row.split(",")

print(f"Student: {name}")
print(f"Subject: {subject}")
print(f"Marks: {int(marks)}")
print(f"Label: {name.upper()}-{subject[:3].upper()}")
This combines parsing, conversion, slicing, and formatting.

Exam-focused points

  • strip() removes leading/trailing spaces only
  • find() returns -1 if not found
  • split() output type is list
  • f-strings are preferred for readable output
  • f"{500:06}" means zero-pad to width 6, giving "000500"
  • for string formatting width, :9 is left, :^9 center, and :>9 right
  • in method chains, track intermediate types (str -> list -> etc.) before choosing answer

Practice questions

  1. Count vowels in a string.
  2. Replace all spaces with _.
  3. Check whether two strings are anagrams (basic approach).