Skip to main content
Anime study buddy

Learning outcomes

By the end of this chapter, you should be able to:
  • create and print strings
  • use indexing and slicing
  • apply basic string operators
  • explain string immutability

Creating strings

s1 = "Python"
s2 = 'College'

Indexing

s = "Python"
print(s[0])   # P
print(s[-1])  # n

Slicing

s = "Statistics"
print(s[0:5])   # Stati
print(s[5:])    # stics
print(s[:4])    # Stat

String operators

a = "Py"
b = "thon"
print(a + b)      # Python
print("ha" * 3)   # hahaha

Immutability

Strings cannot be changed in place.
s = "cat"
# s[0] = "b"  # TypeError
s = "b" + s[1:]
print(s)  # bat

Useful basics

text = "python"
print(len(text))
print("th" in text)

Exam-focused points

  • indexing starts at 0
  • negative index starts from end
  • slice end index is excluded
  • strings are immutable

Practice questions

  1. Take a word and print first and last character.
  2. Reverse a string using slicing.
  3. Print every alternate character from a string.