6.3.3 – Processing and formatting strings

6.3.3 – Processing and formatting strings

Choose string methods for searching, cleaning, splitting and classification. Combine transformations and use the supported format descriptors to produce clear labels, aligned fields and precise decimal displays.

Find a substring or recognise its absence

Two methods locate the first occurrence of a substring, reading left to right. Both return its position when found. Their absent-case behaviour differs.

MethodWhen presentWhen absent
find()First matching indexReturns -1
index()First matching indexRaises ValueError

Both accept optional start and end positions. The search begins at start and stops before end; the returned index still refers to the original string.

Python
reference = "CS-LEVEL-CS"
print(reference.find("CS"))
print(reference.find("CS", 1))
print(reference.index("LEVEL"))
print(reference.find("GCSE"))
Output
0
9
3
-1

Use find when absence is expected and must be handled. A result of 0 is a successful match at the beginning; it is not the same as -1. Check the result before using it as a substring boundary. Otherwise an absent delimiter may silently produce a slice ending one character before the end.

Python
label = "NORTH-27"
dash = label.find("-")
if dash != -1:
    area = label[:dash]
    print(area)
else:
    print("No separator")

Use index when the task guarantees a match or intends a missing substring to be an error. No exception-handling syntax is assumed in this lesson.

Clean, replace and split

Choose a method from the change required. strip removes specified characters repeatedly from both ends, replace substitutes matching substrings throughout, and split returns a list of fields at a separator.

Python
raw = "**red|green|red**"
cleaned = raw.strip("*")
changed = cleaned.replace("red", "amber")
colours = changed.split("|")
print(colours)
Output
['amber', 'green', 'amber']

The intermediate strings are red|green|red and amber|green|amber. raw remains unchanged: strings are immutable and these methods return new values. Assign a returned value if it is needed later.

strip affects the ends, not matching characters in the middle. Its argument describes removable characters rather than one required prefix/suffix. For example, stripping A and B from both ends of ABXBA leaves X. replace can change occurrences anywhere. split with an explicit separator preserves empty fields between consecutive separators: A||B produces three fields, including an empty middle string.

Python
text = " ABXBA "
print(text.strip(" AB"))
print("A||B".split("|"))
Output
X
['A', '', 'B']

Do not assume splitting always yields the number of fields you hoped for. These exercises state the expected format. File processing and validating arbitrary records are separate lessons.

Convert case or classify characters

upper() and lower() return changed strings. The methods beginning with is return Boolean answers instead. They answer different questions: converting ab12 to AB12 is not the same as asking whether ab12 was already uppercase.

MethodTrue when, for the ASCII domain used here
isupper()At least one letter exists and all letters are uppercase
islower()At least one letter exists and all letters are lowercase
isalpha()Nonempty and every character is a letter
isalnum()Nonempty and every character is a letter or digit
isdigit()Nonempty and every character is a digit

Digits and punctuation have no case. Thus AB12! passes isupper but fails isalnum. The text 123 is neither uppercase nor lowercase because it has no cased letter. Empty text gives False for all five classification methods. A minus sign or decimal point makes isdigit False; it does not establish whether arbitrary text represents a valid number.

Python supports characters beyond ASCII. The simple letter/digit examples and task domains here explicitly use ASCII so these rules are unambiguous.

Python
status = "Ready2"
print(status.upper())
print(status.lower())
print(status.isalnum())
print(status.isupper())
print(status)
Output
READY2
ready2
True
False
Ready2

The final line shows that conversion did not change status itself. To retain uppercase text under that name, assign the returned uppercase string.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account