Skip to main content
Anime study buddy

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

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"))

Split and join

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

joined = "-".join(colors)
print(joined)

String formatting

name = "Dhruv"
score = 92
print(f"{name} scored {score}")
print("{} scored {}".format(name, score))

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))

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

Practice questions

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