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)
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))
P N YTH NOHTYP 6
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)
Pune amit AMIT
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)
Uppercase: 3 Lowercase: 11 Digits: 2 Spaces: 4 Others: 1
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"))
hello world Hello World Hello world 5 -1 2 True False priya@college.in
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("@"))
['Amit', 'Priya', 'Ravi', 'Neha']
Amit | Priya | Ravi | Neha
5 words
('rahul', '@', 'gmail.com')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
Priya scored 452/500 Percentage: 90.40% [Priya ] [ Priya] [ Priya ] Fee: βΉ125,000
π― 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:"-" * 20prints a line of 20 dashes.in/not intest for a substring:"cat" in "education"isTrue.==,<,>compare character by character using Unicode values, so"apple" < "banana"isTrueand"Zebra" < "apple"is alsoTrue(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:
\nnew line,\ttab\'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; writes = s.strip(). - Mixing str and int:
"Marks: " + 95raises TypeError. Usestr(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"isFalse. Comparea.lower() == b.lower()when case should not matter.
Next: Day 12 β Tuples, the read-only cousin of lists.