4.4 Strings
A string is also a sequence. It is made of ordered characters, so it can be indexed, sliced, and processed with many string methods.
String methods
Common string methods include:
lower(): convert to lowercase.upper(): convert to uppercase.capitalize(): capitalize the first letter.strip(): remove leading and trailing whitespace.replace(): replace part of a string.
python
s = "Hello World!"
print("[Lower]")
print(s.lower())
print("[Upper]")
print(s.upper())
print("[Capitalize]")
print(s.capitalize())
print("[Strip]")
print(" Hello World!\n \t".strip())
print("[Replace]")
print(s.replace("Hello", "Bye"))String methods usually return a new string instead of modifying the original string.
Loading interactive lab...
Loading concept check...
split() and join()
split() breaks a string into a list. join() combines strings from a list.
python
date_time = "2026/1/14 8:26:51"
date_part, time_part = date_time.split(" ")
year, month, day = date_part.split("/")
hour, minute, second = time_part.split(":")
print("Date parts: year=%s, month=%s, day=%s" % (year, month, day))
print("Time parts: hour=%s, minute=%s, second=%s" % (hour, minute, second))
new_date = "-".join([day, month, year])
new_time = hour + "h" + minute + "m" + second + "s"
print("Reformatted: %s %s" % (new_date, new_time))Output:
text
Date parts: year=2026, month=1, day=14
Time parts: hour=8, minute=26, second=51
Reformatted: 14-1-2026 8h26m51ssplit() and join() are common in text, date, path, and CSV processing. This example splits the date and time into six parts, then rebuilds them into a visibly different display format.
Loading concept check...
Loading practice...