Sub topic 3
Splitting Text Apart and Joining It Back
This chapter assumes basic Python syntax, string indexing, lists, tuples, and simple if statements and for loops.
Splitting and Joining
split returns a list of pieces. With no argument, it treats any run of whitespace as one separator. With an explicit separator, empty fields are preserved. rsplit starts from the right, and splitlines handles line boundaries.
partition splits once and always returns a three-item tuple: text before the separator, the separator, and text after it. join performs the reverse operation. It places its separator between strings from an iterable.
record = "name=Ada=extra"
key, separator, value = record.partition("=")
print(key, value) # name Ada=extra
words = " Python string methods ".split()
sentence = " ".join(words)
print(sentence) # Python string methods
print("a,b,,c".split(",")) # ['a', 'b', '', 'c']
print("a b c".rsplit(" ", 1)) # ['a b', 'c']
print("one\ntwo".splitlines()) # ['one', 'two']Checking Character Types
Character checks answer questions about every character in a string. isdigit, isalpha, and isalnum test digits, letters, and letters-or-digits. isspace tests whitespace. Each returns False for an empty string.
value = "Room42"
print(value.isalnum()) # True
print("42".isdigit()) # True
print(" ".isspace()) # TrueThese checks describe Unicode characters, not only ASCII characters. Validate the exact input rules your application needs.
Mapping and Deleting Characters
str.maketrans creates a translation table. translate applies that table in one pass. Its third argument lists characters to delete.
table = str.maketrans("abc", "xyz")
print("aabbcc".translate(table)) # xxyyzz
delete_vowels = str.maketrans("", "", "aeiou")
print("education".translate(delete_vowels)) # dctnChaining a Cleanup Pipeline
String methods return new strings, so their results can be chained. Keep a pipeline readable by assigning an intermediate result when a step needs explanation.
raw = " Hello, WORLD! "
clean = " ".join(raw.strip("! ").split()).casefold()
print(clean) # hello, world!The split and join pair normalizes internal whitespace. casefold is useful for caseless comparison.
When String Methods Are Not Enough
Use string methods when the rule is literal and straightforward. Use the re module when you need patterns, such as one or more digits, optional punctuation, or word boundaries.
import re
text = "IDs: A12, B305"
ids = re.findall(r"\b[A-Z]\d+\b", text)
print(ids) # ['A12', 'B305']Exercise
What does ", ".join("abc") produce, and why?
Show answer
It produces a, b, c because a string is an iterable of its individual characters, and join places ", " between them.