String Manipulation

beginner20 min

Learning objectives

  • Manipulate strings using built-in Python functions
  • Extract and modify characters and substrings
  • Develop programs that validate and format text input

Learn

AQA 4.1.1.7 — String manipulation

Retrieval: strings are one of the primitive data types from the first lesson of this course - here you'll learn the operations Python provides specifically for working with that type.

Strings support indexing, slicing and a set of built-in operations for inspecting and transforming text.

username = "Aisha_K"

print(len(username))           # 7 - length
print(username[0])             # "A" - first character
print(username[-1])            # "K" - last character
print(username[0:5])           # "Aisha" - substring (slice)
print(username.upper())        # "AISHA_K"
print(username.lower())        # "aisha_k"
print(username.replace("_", " "))  # "Aisha K"

Common mistake

String indexing starts at 0, not 1 — username[0] is the first character. A slice username[0:5] also stops before index 5, giving 5 characters (indexes 0-4), not 6. Off-by-one errors here are one of the most common early Python mistakes.

Building a username generator

first = input("First name: ")
last = input("Last name: ")
username = (first[0] + last).lower()
print(f"Your username is: {username}")

For "Aisha" and "Khan", this produces akhan.

Validating input

String methods are the basis of input validation — a core theme across BTEC and A-level alike:

password = input("Choose a password: ")

has_upper = any(c.isupper() for c in password)
has_digit = any(c.isdigit() for c in password)
long_enough = len(password) >= 8

if has_upper and has_digit and long_enough:
    print("Password accepted.")
else:
    print("Password must be 8+ characters with an uppercase letter and a digit.")

Challenge

Extend the password validator to also require at least one non-alphanumeric character, and report which rule(s) failed rather than a single generic message.

Practise

Apply what you've just learned in the Coding Lab.

Open Coding Lab
Log in to track this lesson on your progress dashboard.
Log in