Pick one character
Every character in a text has a position, starting at 0. text[n] reads one of them, text[-1] reads the last, and len(text) counts them.
- Read a character with a position from the start (
code[0]) or from the end (code[-1]) - Use
lento count characters and explain why the last position islen(text) - 1 - Make a decision from one character, remembering that a character is text, not a number
Codes and IDs in real data often carry meaning in one position. In the Online Retail data, an invoice number that starts with C is a cancellation. A Runtime Market SKU such as HOM-52782 starts with its category. The first digit of a US ZIP code names a region of the country. To read one character you need its position, also called its index.
Positions start at 0, so sku[0] is the first character and sku[1] the second. A negative position counts back from the end, so sku[-1] is the last character. len(sku) counts the characters, which makes the last position len(sku) - 1.
Run each example to see what it prints. Running examples doesn't count toward progress.
sku = "HOM-52782" print(sku[0], sku[1], sku[2]) print(sku[4]) print(sku[-1]) print(len(sku)) print(sku[len(sku) - 1])
If you ask for a position that doesn't exist, Python stops with an error instead of giving back an empty answer. The most common slip is to use the length itself as a position.
sku = "HOM-52782" print(len(sku)) print(sku[len(sku)])
An index is most useful when a decision depends on one character. Combine it with if (see Conditional Logic) and len to check a record before you trust it. A CFPB complaint has a state code and a ZIP code. A state code has 2 characters and a ZIP code has 5. A ZIP code that starts with 9 is on the West Coast.
state = "MI" zip_code = "48301" if len(state) == 2 and len(zip_code) == 5: print("Location looks complete") else: print("Location needs checking") area = zip_code[0] if area == "9": print("West Coast ZIP") else: print("ZIP area", area)
When to use it: whenever one position has a fixed meaning, such as a prefix letter, a check digit at the end, or a separator at a known place. Mistakes to avoid:
- Counting positions from 1 instead of 0.
- Using
len(text)as the last position. - Comparing a character with a number.
zip_code[0] == 4is always False, because"4"is text. The concept check below runs this one.
- Positions start at 0. A negative position counts from the end, so
text[-1]is the last character. len(text)counts characters, and the last position islen(text) - 1. Asking for positionlen(text)raises IndexError.- A character is text: compare it with
"4", not 4, or convert it withint. - Next: read a whole run of characters at once with a slice.