Programming in Python · Lesson 5

Character and String Data Types — Programming Examples

Five runnable Python examples covering character data, character methods, escape sequences, string indexes, string functions, substrings, concatenation, and typecasting.

  • characters
  • strings
  • escape-sequences
  • string-methods
  • substrings
  • concatenation
  • type-casting

Use these short, runnable examples as demonstration checkpoints. Ask students to predict the output before you run each one.

  1. Character data, digits vs. numbers, and output format
first_initial = "N"
middle_initial = "L"
first_digit = "2"
second_digit = "5"

# Digits in quotes are characters, so + glues them together
print(first_digit + second_digit)

# Without quotes they are integers, so + adds them
print(2 + 5)

# Three ways to format character output
print(first_initial + " " + middle_initial)   # space inserted with a string literal
print(first_initial, middle_initial)          # comma adds a space automatically
print(first_initial)                          # one print() per line
print(middle_initial)

Teaching point: A character is a single letter, digit, or symbol stored in quotes. “2” and “5” are characters, so + concatenates them into 25, while 2 + 5 adds integers to 7. Use a “ “ literal, a comma in print(), or separate print() calls to control how characters appear.

  1. Character methods: checking and changing case
initial = input("Enter your middle initial: ")
initial = initial.upper()

print("Stored initial:", initial)
print("Is a letter?", initial.isalpha())
print("Is a digit?", initial.isdigit())
print("Lowercase version:", initial.lower())

section = "3"
print("Section is a letter?", section.isalpha())
print("Section is a digit?", section.isdigit())

Teaching point: Methods are applied with a period after the variable, as in initial.upper(). isalpha() and isdigit() return True or False, and upper()/lower() return a new value, so the result must be stored back in a variable to keep it.

  1. String literals, escape sequences, and indexes
course_title = "Programming in Python"
quote = "My instructor said, \"Indexes start at zero.\""
file_path = "C:\\Users\\student\\lab05.py"

print(quote)
print(file_path)
print("Name\tGrade\nAva\tA\nBen\tB")

# Each character has an index, starting at [0]
print(course_title[0])    # P
print(course_title[3])    # g
print(course_title[15])   # P (the P in Python)

Teaching point: A backslash starts an escape sequence: " embeds a quotation mark, \ a backslash, \n a new line, and \t a tab. Every character in a string has an index starting at [0], and spaces count as characters, which is why the P in Python is at index 15.

  1. String functions, case sensitivity, and substrings
book_title = "programming with python"
search_term = "PYTHON"

print(len(book_title))
print(book_title.title())
print(book_title.upper())
print(book_title.count("o"))
print(book_title.find("w"))
print(book_title.find("java"))
print(book_title.startswith("pro"))
print(book_title.endswith("python"))

# Case sensitivity: the same word in different case does not match
print("python" == search_term)
print("python" == search_term.lower())

# Substrings: [start:end] stops BEFORE the end index
first_word = book_title[0:11]
last_word = book_title[17:23]
print(first_word)
print(last_word)

Teaching point: len() is a function (the string goes inside the parentheses), while the others are methods. find() returns the index of the first match or -1 if there is none. “python” and “PYTHON” have different ASCII codes, so convert both to the same case before comparing. A substring [start:end] includes start but stops before end.

  1. Concatenation and typecasting: student record builder
first_name = input("First name: ")
last_name = input("Last name: ")
student_id = 4127
due_date = "21 October"

# Concatenate variables into a new variable
full_name = last_name + ", " + first_name

# str() typecasts the integer so it can be concatenated
# (full_name + " #" + student_id would raise a TypeError)
record = full_name + " #" + str(student_id)
print(record)

# int() typecasts a substring of digits so it can be used in math
day = int(due_date[0:2])
late_day = day + 2
print("Due " + due_date + ", accepted late until " + str(late_day) + due_date[2:])

Build sequence:

  1. Start with hard-coded first and last names and print full_name.
  2. Replace them with input().
  3. Try concatenating student_id directly to see the TypeError, then fix it with str().
  4. Slice the day out of due_date, convert it with int(), and add 2.

Exit-ticket prompts

  1. What does print(“4” + “7”) output, and why?
  2. Write a string literal that prints: She said “Hi”
  3. Given word = “Alphabet”, what is word[2]?
  4. What does “banana”.find(“n”) return?
  5. Fix the error: age = 19; print(“Age: “ + age)

Answer key

  1. 47, because both values are characters, so + concatenates instead of adding
  2. “She said "Hi"”
  3. p
  4. 2
  5. print(“Age: “ + str(age))