Sub topic 2
Splitting Text into Lines with `splitlines`
Assume you know basic Python syntax, strings, lists, tuples, method calls, and for loops. Python strings are immutable, so these methods return new values rather than changing the original string.
Splitting text into lines with `splitlines`
str.splitlines() returns a list containing one item for each line. It recognizes common line endings, including \n, \r\n, and \r.
Unlike split("\n"), splitlines() does not leave a carriage return attached to a line and does not add a final empty item when the text ends with a newline.
data = "one\ntwo\r\nthree\n"
print(data.splitlines())
print(data.splitlines(keepends=True))Output:
['one', 'two', 'three']
['one\n', 'two\r\n', 'three\n']The optional keepends=True preserves each line-ending sequence. This is useful when you need to write the lines back without changing their formatting.
Dividing at the first or last separator
partition(separator) always returns a three-item tuple: the text before the first separator, the separator itself, and the text after it.
address = "[email protected]"
name, marker, domain = address.partition("@")
print(name)
print(domain)
print("a.b.c".rpartition("."))rpartition() searches from the right, so it is useful for file extensions or final path components. If the separator is missing, partition() returns the original string followed by two empty strings.
Combining strings with `str.join`
join() is called on the separator and receives an iterable of strings.
parts = ["red", "green", "blue"]
print(", ".join(parts))
print("".join(parts))The items must already be strings. Convert other values before joining:
numbers = [1, 2, 3]
text = ", ".join(str(number) for number in numbers)
print(text)join() is usually clearer and more efficient than adding strings repeatedly in a loop. Since strings are immutable, repeated + can create a new string on every iteration.
Exercise
Which method returns the final component of "logs/app/server.txt" after the last slash?
Show answer
Use "logs/app/server.txt".rpartition("/"), then read the third item of the returned tuple.