Programming in Python · Lesson 5
Character and String Data Types
Characters, strings, ASCII storage, escape sequences, indexing, string methods, slicing, concatenation, and typecasting in Python.
Lesson purpose
This lesson moves from numbers to text. Students learn how Python represents a single character, how characters combine into strings, how to reach individual characters by index, how to use the most common string functions and methods, and how to join strings together or convert between strings and numbers. Almost every program students write from here on reads, builds, or displays text, so this vocabulary will be used constantly.
Because the class already knows C# and JavaScript, much of this will feel familiar. The most useful thing to emphasize is where Python differs: Python has no separate character type, strings are immutable, and Python will not silently mix strings and numbers with + the way JavaScript does.
Learning objectives
By the end of the lesson, students should be able to:
- Identify data that is classified as a character and initialize a variable with character data.
- Describe the quoting conventions for character and string literals.
- State the storage used for an ASCII character and explain the difference between a digit character and a number.
- Format output so values are separated by spaces or placed on separate lines.
- Use common methods for testing and changing character data.
- Explain that a string is a sequence of characters stored in consecutive memory locations, each with an index starting at 0.
- Decide when an escape sequence is needed and use the common escape sequences.
- Find the length of a string, change its case, and explain why case sensitivity matters.
- Find the position of a character and retrieve a substring with slice notation.
- Explain concatenation, use the
+operator to join strings in output and in variables, and name which data types can be concatenated. - Explain coercion and typecasting, and convert values with
str()andint().
1. Characters
What counts as a character
A character is the classification programmers use for a value that holds a single letter of the alphabet, a single numeral from 0 to 9, or a symbol. Examples: a person’s middle initial, a single menu choice such as "y" or "n", or one letter in an alphabet program for young children.
Talking points:
- Letters:
"a","Z" - Digits:
"0"through"9"(as text, not as numbers) - Symbols:
"$","?", a space" "
Initializing character data
Character literals are surrounded by quotes. Python accepts double quotes or single quotes; the book uses double quotes, and this class will do the same for consistency.
first_letter = "a"
print(first_letter)
Output:
a
- Line 1 stores the character
ain the variablefirst_letter. - The quotes are not stored. They only tell Python where the literal starts and ends.
- Line 2 displays the value; the output shows
awithout quotes.
General pattern:
variable_name = "x" # where x is a single character
Python vs. C# and Java
In C# and Java, char is its own type and uses single quotes ('a'), while strings use double quotes. Python has no char type. A “character” in Python is simply a string whose length is 1, so "a" and 'a' are the same kind of value: str. JavaScript behaves the same way as Python here.
Quick check: ask students to predict type("a"). The answer is <class 'str'>.
2. Character memory allocation and ASCII
Character data is stored as a numeric code. The book presents ASCII (American Standard Code for Information Interchange), an encoding that assigns a unique eight-bit pattern to each common character.
- The letter
ais stored as01100001, which is decimal 97. - Every uppercase letter, lowercase letter, numeral, and keyboard symbol has its own ASCII value.
- One ASCII character fits in one byte (eight bits) of memory.
Students can see the codes directly:
print(ord("a")) # 97
print(bin(ord("a"))) # 0b1100001
print(chr(97)) # a
ord()returns the numeric code for a character.bin()shows that number in binary.chr()goes the other direction, from code to character.
Modern note: Python 3 strings are actually Unicode, not plain ASCII. Unicode includes every ASCII character with the same code numbers (so
ord("a")is still 97), and it adds characters from other languages, symbols, and emoji. The one-byte-per-character idea is accurate for ASCII text but is a simplification for Unicode text in general. For this course, thinking in ASCII terms is fine.
3. Digits versus numbers
The quotes around a character literal matter most when the value is a digit.
2without quotes is an integer; it can be used in arithmetic."2"with quotes is a character (a string); it is just a symbol and has no numeric value.
Prediction question from the book:
first_digit = "2"
second_digit = "5"
print(first_digit + second_digit)
Ask: What will this print? Many students expect 7.
Output:
25
- Because both values are strings,
+joins them instead of adding them. - If the assignments were
2and5(no quotes), the result would be7.
How they are stored:
| Value | Type | Stored as |
|---|---|---|
a_digit = "5" |
string | ASCII code for the symbol 5: 00110101 |
an_integer = 5 |
integer | binary number five: 00000101 |
Teaching point: any data that will be used in a calculation should be stored as a numeric type, not as characters.
JavaScript connection: in JavaScript, "2" + 5 produces "25" because JavaScript quietly converts the number to a string. Python refuses to mix types that way (see Section 11).
4. Character output format
The previous program printed 25, which looks like the number twenty-five even though it is really the digit 2 followed by the digit 5. Two ways to make the output clearer:
Separated by a space
first_digit = "2"
second_digit = "5"
print(first_digit + " " + second_digit)
print(first_digit, second_digit)
Output:
2 5
2 5
- Line 3 builds one string by inserting a literal space
" "between the two values. - Line 4 passes two separate arguments to
print(). When values are separated by commas,print()automatically puts one space between them.
On separate lines
first_digit = "2"
second_digit = "5"
print(first_digit)
print(second_digit)
Output:
2
5
Each print() call ends with a line break, so one print() per value places each value on its own line.
5. Character manipulation methods
Python provides built-in tools, called methods, for working with character data. A method is applied to a value by writing the value, a period, the method name, and parentheses:
"a".upper()
Changing case
upper() produces the uppercase version of a character. If the character has no uppercase version (for example, a symbol such as "#"), it is returned unchanged.
initial = input("Enter initial: ")
initial = initial.upper()
print(initial)
Sample run:
Enter initial: b
B
- Line 1 uses
input()to collect a character from the keyboard and store it ininitial. - Line 2 calls
upper(), which creates a new uppercase value; assigning it back toinitialreplaces the old lowercase value. - Line 3 displays the result.
A common use: making sure a stored middle initial is always uppercase regardless of how the user typed it.
Common character methods
| Purpose | Example | Data | Result |
|---|---|---|---|
| Is it a letter of the alphabet? | initial.isalpha() |
initial = "a" |
True |
choice.isalpha() |
choice = "2" |
False |
|
| Is it a digit? | initial.isdigit() |
initial = "a" |
False |
choice.isdigit() |
choice = "2" |
True |
|
| Change to uppercase | initial.upper() |
initial = "a" |
"A" |
| Change to lowercase | initial.lower() |
initial = "A" |
"a" |
Talking points:
isalpha()andisdigit()return Boolean values (TrueorFalse). They are useful for validating user input before using it.upper()andlower()return a new string; they never change the original value.
6. Strings
A string is a sequence of characters. Python’s string data type (str) is used for words, phrases, sentences, and other text. As with characters, string literals are enclosed in quotes; again, this class uses double quotes.
| Code | What it does |
|---|---|
your_name = "" |
Initializes your_name as an empty string (a string with no characters). |
message = "likes alphabet soup." |
Initializes a variable containing a string. Quotes are required in the program. |
print("What is your name? ") |
Displays a prompt containing a string. |
your_name = input() |
Collects a user-typed string such as Skylar Jones. The user does not type quotes. |
print(your_name, message) |
Displays the contents of your_name, a space, then the contents of message. |
Putting it together, the Alphabet Soup program:
your_name = input("What is your name? ")
message = "likes alphabet soup."
print(your_name, message)
Sample run:
What is your name? Skylar Jones
Skylar Jones likes alphabet soup.
- Line 1 displays the prompt and stores whatever the user types as a string.
- Line 2 stores a string literal; the quotes are not part of the stored value.
- Line 3 prints both values separated by one space (because of the comma).
7. Escape sequences
A problem arises when the text itself contains quotation marks, such as song titles or quotes:
fun_fact = "Philip Parker wrote the song "Alphabet Soup."" # causes an error
Python treats the second double quote as the end of the string, so it sees "Philip Parker wrote the song " as the whole string and cannot make sense of Alphabet Soup."" that follows. The result is a syntax error.
An escape sequence fixes this. It begins with a backslash \ and embeds a special instruction inside a string. \" places a quotation mark in the string without ending it:
fun_fact = "Philip Parker wrote the song \"Alphabet Soup.\""
print(fun_fact)
Output:
Philip Parker wrote the song "Alphabet Soup."
Do not put a space after the backslash; \ " is not the same as \".
Common escape sequences
| Escape sequence | Name | Use |
|---|---|---|
\" |
Quotation mark | For strings that include double quotation marks |
\\ |
Backslash | For strings that include a backslash (for example, a Windows file path) |
\n |
Newline | To insert a line break inside a string |
\t |
Tab | To insert a tab inside a string |
Prediction question:
review = "This song's kind of \n \"SOUPY!\""
print(review)
Output:
This song's kind of
"SOUPY!"
\nmoves the rest of the string to a new line.- The space typed after
\nstays in the string, so the second line begins with a space. \"produces the literal quotation marks aroundSOUPY!.- The apostrophe in
song'sneeds no escape because the string is enclosed in double quotes.
Python alternative worth mentioning: because Python allows either quote style, 'He said "hi"' also works without escapes. The book’s convention is double quotes plus \" when needed, and that is what students should practice.
8. String memory and indexes
Strings are stored in a succession of consecutive memory locations, one character per location. Each character has an index: a number that indicates its position in the string. Indexes start at 0.
For company_name = "Campbell's":
| Character | C | a | m | p | b | e | l | l | ’ | s |
|---|---|---|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Indexes are written in square brackets after the variable name:
company_name = "Campbell's"
letter = company_name[0]
print(letter)
Output:
C
company_name[0]retrieves the first character.- A common use is checking that the first letter of a name is uppercase.
Check for understanding: What would you change to get the third letter? Change the index to 2, because counting starts at 0:
letter = company_name[2] # "m"
Emphasize: the third character is at index 2, the tenth at index 9. The last valid index is always one less than the length. Using an index past the end (for example, company_name[10]) causes an IndexError.
Preview (not in this module’s reading, but students coming from other languages often ask): Python also allows negative indexes, so company_name[-1] is the last character, "s".
9. String functions and methods
Programming languages provide many tools for manipulating strings. Four common tasks:
- Find the length of a string.
- Change the case of a string.
- Check whether a string contains a specific character.
- Retrieve a substring from a longer string.
Length with len()
Knowing a string’s length helps ensure a string is complete, supports algorithms such as reversing a string, and checks that input is not too long for a data entry box.
the_length = len(variable_name)
len() returns an integer. Note the format difference: len() is a function that takes the string inside its parentheses, while upper() is a method called with a period after the string.
alphabet = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
the_length = len(alphabet)
print(the_length)
Output:
25
Ask: The alphabet has 26 letters, but this reports 25. Which letter is missing? Answer: N. This is a good illustration of len() as a completeness check.
Case methods and other useful string methods
Everything that works on character data also works on string data, because to Python a character is just a string of length 1.
| Method | Description | Example | Output |
|---|---|---|---|
count() |
Number of times a value occurs in the string | "banana".count("a") |
3 |
endswith() |
True if the string ends with the value |
"alphabet".endswith("bet") |
True |
find() |
First index of the value, or -1 if not found | "apple".find("p") |
1 |
startswith() |
True if the string starts with the value |
"caterpillar".startswith("cat") |
True |
title() |
Capitalizes the first letter of each word | "hello world!".title() |
Hello World! |
upper() / lower() |
Uppercase or lowercase version | "Soup".upper() |
SOUP |
Key point: none of these methods change the original string. Python strings are immutable. Each method creates a new value, which can be stored in a new variable (or assigned back to the same one). This matches C# and JavaScript, where strings are also immutable.
Case sensitivity
The string "Soup" is not equal to "SOUP" or "soup". Uppercase and lowercase letters have different codes: uppercase S is 01010011, lowercase s is 01110011. Because the codes differ, the strings do not match.
This idea is called case sensitivity. Passwords and variable names are common examples of case-sensitive data. It also matters for searching and sorting: a grocery inventory search for "alphabet soup" will not match "Alphabet Soup" unless the program handles case.
One solution is to compare lowercase versions of both strings:
first_item = "Soup"
second_item = "soup"
if first_item.lower() == second_item.lower():
print("The words are the same.")
==compares the values on either side for equality (decisions are covered fully in the next lesson; here it is a preview).lower()converts every letter in each string to lowercase before the comparison, so differences in case no longer matter.- The original variables are unchanged.
Finding the location of a character with find()
You can check whether a string contains a specific character, and where. A space in a string suggests it holds more than one word; a comma might indicate a list. Knowing the position lets a program later break the string apart.
find() returns the index of the first occurrence of the specified value (remember indexing starts at 0), or -1 if the value is not present.
product_name = "Campbell's Alphabet Soup"
where = product_name.find(" ")
print(where)
Output:
10
Ask students to count: Campbell's occupies indexes 0 through 9, so the first space is at index 10.
Retrieving a substring
A substring is part of a longer string. Working with substrings is a component of search engines and many text-processing algorithms. Retrieve one by giving the starting index and ending index in square brackets:
new_string = variable_name[start:end]
The character at end is not included.
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sub_string = alphabet[3:8]
print(sub_string)
Output:
DEFGH
- Index 3 is
D(A is 0, B is 1, C is 2). - The slice continues up to, but not including, index 8 (
I), so it ends atH(index 7). - Quick rule: the number of characters returned is
end - start(here, 8 - 3 = 5).
JavaScript connection: this behaves like "ABC...".slice(3, 8) or substring(3, 8). In C#, Substring(3, 5) takes a start and a length, which is a common source of confusion when switching languages.
10. Concatenation
Concatenation means chaining two or more values together in sequence. In Python, + is the concatenation operator when both operands are strings.
Concatenating during output
Storing first and last names in separate variables gives flexibility, such as displaying “Parker, Philip” instead of “Philip Parker.” The book first shows the plan in pseudocode:
prompt the user for their first and last names
read the first and last names
display a message in last name, first name format
Expected output:
What is your first name? Philip
What is your last name? Parker
Hello, Philip
You are filed as Parker, Philip
In Python:
first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
print("Hello,", first_name)
print("You are filed as", last_name + ", " + first_name)
- Line 3 uses a comma, so
print()supplies the space afterHello,. - Line 4 builds
"Parker, Philip"with two+operators; the literal", "supplies the comma and space. The comma before it separates that result from"You are filed as".
Point out the two ways to combine output: a comma passes separate items to print() (spaces added automatically, and non-strings are allowed), while + builds one new string (you control every space, and all pieces must be strings).
Concatenating variables
Concatenation is not just for output. The result can be stored in a new variable:
company_name = "Campbell's"
soup_name = "Alphabet Soup"
product_name = company_name + " " + soup_name
print(product_name)
Output:
Campbell's Alphabet Soup
product_nameholds the combined text with a space in between.- Best practice: store the combined result in a new, clearly named variable. Putting
company_name + soup_nameback intocompany_namewould work, but the variable name would no longer describe its contents.
11. Coercion and typecasting
Strings can be concatenated with other strings (and characters, since those are strings too) but not with integers or floating-point numbers. Mixing types causes an error:
house_number = 101
street_name = "Main Street"
print(house_number)
print(street_name)
full_address = house_number + " " + street_name
print(full_address)
Output:
101
Main Street
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Read the error message with students: Python cannot use + with an int on one side and a str on the other.
Two terms to define:
- Coercion: the language automatically converting one data type to another. JavaScript coerces freely (
101 + " Main Street"works there). Python does not coerce between numbers and strings for+, which is why the error occurs. - Typecasting: the programmer explicitly converting a value from one data type to another with a conversion function.
Integer to string with str()
converted_string = str(variable_name)
house_number = 101
street_name = "Main Street"
full_address = str(house_number) + " " + street_name
print(full_address)
Output:
101 Main Street
str() converts an integer or floating-point number into a string so it can be concatenated. house_number itself is still an integer afterward.
String to integer with int()
Converting a string to an integer is useful when a string contains digits that are needed for a calculation. The string passed to int() must contain an integer value, or Python raises a ValueError.
integer_variable = int(string_variable)
today = "15 February"
today_substring = today[0:2]
day_number = int(today_substring)
tomorrow = day_number + 1
print(tomorrow)
Output:
16
- Line 2 slices the first two characters,
"15". - Line 3 converts that text into the integer
15. - Line 4 does arithmetic that would be impossible on the string.
Connection back to earlier modules: input() always returns a string, so int(input(...)) or float(input(...)) is required whenever user input will be used in a calculation.
Preview for later: Python’s f-strings, such as f"{house_number} {street_name}", format mixed types without manual str() calls and will feel familiar to students who know C# interpolated strings or JavaScript template literals. This module teaches + and str() first so students understand what the conversion is doing.
Classroom application
Use these short tasks in class or as warm-ups. Each builds on the book’s examples.
- Initial formatter. Ask for a first name, middle initial, and last name. Display the name as
Last, First M.with the initial forced to uppercase usingupper(). - Digit trap. Have students run
print("4" + "4")andprint(4 + 4), then explain the different outputs using the terms string, integer, and concatenation. - Quote practice. Print the sentence
The menu said "Soup of the Day" twice.using an escape sequence, then print the same sentence across two lines with\n. - Index hunt. Given
word = "Mississippi", predict and then checkword[0],word[4],len(word),word.count("s"),word.find("s"), andword[2:6]. - Case-insensitive match. Ask the user for a favorite soup and print a message if it matches
"Alphabet Soup"regardless of case. - Address builder. Ask for a house number with
int(input(...)), add 2 to get the next house on the same side of the street, and print both full addresses usingstr()and+.
Common misconceptions
- “
"2" + "5"should be 7.” Quoted digits are text;+joins strings. Convert withint()first if arithmetic is intended. - “Python has a
chartype likeC#.” It does not. A single character is astrof length 1. - “The quotes are part of the stored value.” Quotes only mark where a literal starts and ends; they are not stored or printed.
- “The first character is at index 1.” Indexing starts at 0. The last index is
len(s) - 1. - “The end index in a slice is included.”
s[3:8]stops before index 8. - “
upper()changes the original string.” String methods return a new string. Assign the result if you want to keep it. - “
find()returns False when the value is missing.” It returns-1. - “
"Soup" == "soup"is True.” String comparison is case sensitive; normalize withlower()orupper()before comparing. - “Python will convert the number for me like JavaScript.” Python raises a
TypeErrorforint + str. Usestr()explicitly (or pass items toprint()with commas). - “A space after the backslash is fine.”
\ "is not an escape sequence for a quote; write\"with nothing in between.
Lesson summary
- A character is a single letter, digit, or symbol. In Python it is simply a string of length 1, written in quotes (double quotes by class convention).
- Character data is stored as numeric codes. ASCII uses eight bits (one byte) per character;
ais 97. Python 3 uses Unicode, which includes ASCII. - The digit
"5"and the integer5are stored differently and behave differently. Store values used in calculations as numbers. print()separates comma-separated items with a space; separateprint()calls produce separate lines.- Methods such as
isalpha(),isdigit(),upper(), andlower()test and transform characters and strings. - A string is a sequence of characters in consecutive memory locations, each with an index beginning at 0.
- Escape sequences start with a backslash:
\",\\,\n, and\t. len()returns a string’s length;count(),find(),startswith(),endswith(), andtitle()are other common tools. String methods return new values because strings are immutable.- String comparisons are case sensitive; normalize case when case should not matter.
s[start:end]returns a substring that stops just beforeend.+concatenates strings in output or into new variables.- Python does not coerce numbers to strings for
+; typecast withstr()andint().
Course Notes