Board Formulas
🐍 PythonπŸ“… Day 11

Strings in Python

Index, slice and loop over strings, use the most useful string methods, and format output neatly with f-strings.

🎯

Learning objectives

  • β†’Index and slice strings, and loop over their characters
  • β†’Use common string methods such as strip(), find(), split() and join()
  • β†’Explain why strings are immutable and how to build a changed copy
  • β†’Format output with f-strings: decimals, alignment and commas

πŸ’‘ Key points

  • A string is an ordered sequence of characters. Indexing and slicing work exactly like lists (Day 8): s[0], s[-1], s[1:4], s[::-1].
  • Strings are immutable: s[0] = 'X' raises TypeError. Methods such as upper() and replace() return a NEW string, so store the result.
  • + joins strings, * repeats them, and in checks for a substring. All comparisons are case-sensitive.
  • find() returns -1 when the text is not found; index() raises ValueError instead.
  • split() breaks a string into a list of words; 'sep'.join(list) glues a list of strings back together.
  • isupper(), islower(), isdigit(), isalpha(), isalnum() and isspace() test the contents and return True or False.
  • f-strings put values inside text: f'{x:.2f}' gives 2 decimals, f'{name:>10}' right-aligns in a width of 10.

πŸ’» Code examples(6)

#1Indexing, slicing and length
python
word = "PYTHON"
print(word[0], word[-1])    # first and last
print(word[1:4])            # index 1, 2, 3
print(word[::-1])           # reversed
print(len(word))
Output
P N
YTH
NOHTYP
6
Positions start at 0 and the stop index of a slice is excluded, just like lists. A slice of a string is a new string.
#2Strings are immutable
python
city = "pune"
# city[0] = "P"   # TypeError: 'str' object does
#                 # not support item assignment
city = "P" + city[1:]       # build a new string
print(city)

name = "amit"
name.upper()                # result thrown away!
print(name)
name = name.upper()         # store the new string
print(name)
Output
Pune
amit
AMIT
You cannot change a character in place. Build a new string with slicing and +, and always assign a method's result back to a variable.
#3Counting character types with a loop
python
text = "Amit scored 95 in CS!"
upper = lower = digits = spaces = others = 0
for ch in text:
    if ch.isupper():
        upper += 1
    elif ch.islower():
        lower += 1
    elif ch.isdigit():
        digits += 1
    elif ch.isspace():
        spaces += 1
    else:
        others += 1
print("Uppercase:", upper)
print("Lowercase:", lower)
print("Digits:", digits)
print("Spaces:", spaces)
print("Others:", others)
Output
Uppercase: 3
Lowercase: 11
Digits: 2
Spaces: 4
Others: 1
A for loop visits one character at a time. The is...() methods make classifying each character easy.
#4Useful string methods
python
s = "  hello world  "
print(s.strip())
print(s.strip().title())
print(s.strip().capitalize())

email = "priya@school.in"
print(email.find("@"))
print(email.find("#"))      # not found
print(email.count("o"))
print(email.startswith("priya"))
print(email.endswith(".com"))
print(email.replace("school", "college"))
Output
hello world
Hello World
Hello world
5
-1
2
True
False
priya@college.in
strip() removes spaces (and tabs or newlines) at both ends; lstrip/rstrip do one side. title() capitalises every word; capitalize() only the first letter of the string, and makes the rest lowercase.
#5split, join and partition
python
line = "Amit,Priya,Ravi,Neha"
names = line.split(",")
print(names)
print(" | ".join(names))

sentence = "Python is easy to learn"
print(len(sentence.split()), "words")

print("rahul@gmail.com".partition("@"))
Output
['Amit', 'Priya', 'Ravi', 'Neha']
Amit | Priya | Ravi | Neha
5 words
('rahul', '@', 'gmail.com')
split() with no argument splits on any whitespace, which makes word counting easy. partition() always returns 3 parts: before, separator, after.
#6f-string formatting
python
name = "Priya"
marks, total = 452, 500
pct = marks / total * 100
print(f"{name} scored {marks}/{total}")
print(f"Percentage: {pct:.2f}%")
print(f"[{name:<10}]")      # left-align
print(f"[{name:>10}]")      # right-align
print(f"[{name:^10}]")      # centre
print(f"Fee: β‚Ή{125000:,}")  # comma separator
Output
Priya scored 452/500
Percentage: 90.40%
[Priya     ]
[     Priya]
[  Priya   ]
Fee: β‚Ή125,000
Anything after the colon inside { } is a format spec. :.2f rounds to 2 decimals, < > ^ align within a width, and , adds thousands separators.

🎯 Practice

Q1. What is the output of print('KENDRIYA'[2:5])?+

NDR β€” indexes 2, 3 and 4. The stop index 5 is excluded.

Q2. Write a program that checks whether a word entered by the user is a palindrome.+

w = input('Enter a word: ').lower() if w == w[::-1]: print('Palindrome') else: print('Not a palindrome')

Q3. What is the difference between find() and index()?+

Both return the position of the first match. If the text is not present, find() returns -1 while index() raises ValueError.

Q4. Why does name.upper() on its own not change name?+

Strings are immutable. upper() returns a new string and leaves the original alone. Write name = name.upper() to keep the result.

Q5. Count the words in s = 'I love coding in Python'.+

print(len(s.split())) # 5

πŸ“ Notes

String operators at a glance

  • + joins: "Board" + "Exam" gives "BoardExam".
  • * repeats: "-" * 20 prints a line of 20 dashes.
  • in / not in test for a substring: "cat" in "education" is True.
  • ==, <, > compare character by character using Unicode values, so "apple" < "banana" is True and "Zebra" < "apple" is also True (capital letters come first).

ord() and chr()

Every character has a number (its Unicode code point). ord() gives the number and chr() goes back:

print(ord("A"), ord("a"))    # 65 97
print(chr(66))               # B

This is handy for tricks like shifting letters in a simple cipher.

Escape sequences and raw strings

Inside quotes, a backslash starts a special character:

  • \n new line, \t tab
  • \' and \" put a quote inside the same kind of quotes
  • \\ a real backslash

A raw string, r"C:\new\test", treats backslashes as normal characters. You will find this useful for Windows file paths on Day 17.

Common mistakes

  • Trying to change one character: s[0] = "A" fails. Build a new string instead.
  • Forgetting to store the result: s.strip() alone does nothing useful; write s = s.strip().
  • Mixing str and int: "Marks: " + 95 raises TypeError. Use str(95) or, better, an f-string.
  • Off-by-one slices: s[0:3] gives 3 characters (indexes 0, 1, 2), not 4.
  • Case surprises: "Delhi" == "delhi" is False. Compare a.lower() == b.lower() when case should not matter.

Next: Day 12 β€” Tuples, the read-only cousin of lists.