Lesson explanation
After this lesson, you will be able to:
Python strings can use single quotes, double quotes, or triple quotes. Choose the quote style that keeps the text readable; triple-quoted strings are useful when the value itself spans several lines.
A string is an ordered sequence of characters. Indexing reads one character, slicing reads a range, and len() returns the number of characters:
code = "API-204"
first = code[0]
numberStrings are immutable. Methods such as strip(), lower(), upper(), and replace() return new strings instead of modifying the original value.
split() turns one string into parts, while join() combines string parts using a chosen separator. This pair is useful for commands, routes, tags, records, and imported text.
💡 Tip: Calling
split()with no argument treats repeated whitespace as one separator, which is useful for messy human-entered text.
Use a different outer quote when the text already contains quotation marks. Triple quotes preserve multiple lines.
event = 'Service "billing" restarted'
notice = """Maintenance window
Starts at 02:00 UTC"""
print(event)
print(notice)Output:
Service "billing" restarted
Maintenance window
Starts at 02:00 UTCIndexes start at 0. Negative indexes count from the end, and slices exclude the ending position.
ticket = "INC-4821"
print(ticket[:3])
print(ticket[-4:])
print(len(ticket))Output:
INC
4821
8String methods return a new value, so store or use the result.
raw_status = " Pending Review "
clean_status = raw_status.strip().upper()
print(clean_status)Output:
PENDING REVIEWSplit using the input separator, then join the parts using the desired output separator.
record = "api,worker,scheduler"
parts = record.split(",")
print(" | ".join(parts))Output:
api | worker | scheduler| Goal | Python |
|---|---|
| Multi-line string | """line one\nline two""" |
| String length | len(text) |
| First character | text[0] |
| Slice from index 4 onward | text[4:] |
| Remove outer whitespace | text.strip() |
| Normalize case | text.lower() / text.upper() |
| Replace text | text.replace(old, new) |
| Split into parts | text.split(separator) |
| Join string parts | separator.join(parts) |
strip() removes repeated whitespace from the middle.