A large part of working with text consists of cutting it into pieces, joining them again and locating specific parts. Python has specific methods for each task.
split: dividing into pieces
sentence = "the sun rises in the east"
print(sentence.split()) # ['the', 'sun', 'rises', 'in', 'the', 'east']
print("a,b,c".split(",")) # ['a', 'b', 'c']
print("a,b,c,d".split(",", 2)) # ['a', 'b', 'c,d'] (at most 2 cuts)
Without arguments, split() separates by any amount of whitespace and discards the empty pieces. If you give a separator, every occurrence cuts, even if there are two in a row:
print("a b".split()) # ['a', 'b']
print("a b".split(" ")) # ['a', '', '', 'b']
splitlines: dividing into lines
text = "first\nsecond\nthird"
print(text.splitlines()) # ['first', 'second', 'third']
join: joining
join is the method of the separator: it is called on the text you want to put between the elements, and receives the list:
words = ["the", "sun", "rises"]
print(" ".join(words)) # the sun rises
print("-".join(words)) # the-sun-rises
print("".join(words)) # thesunrises
All the elements must be texts. To join numbers you have to convert them first:
numbers = [1, 2, 3]
print(",".join([str(n) for n in numbers])) # 1,2,3
Building a text with join is much more efficient than concatenating with += inside a long loop.
partition: cutting at the first occurrence
partition(sep) always returns a tuple of three parts: what comes before, the separator and what comes after. It is ideal for formats like key=value or user@domain:
user, _, domain = "ana@mail.com".partition("@")
print(user) # ana
print(domain) # mail.com
print("no_at_sign".partition("@")) # ('no_at_sign', '', '')
Searching
| Method | What it does | Example |
|---|---|---|
in | checks whether it is there | "sun" in "the sun" → True |
find(x) | position of the first occurrence, or -1 | "banana".find("na") → 2 |
index(x) | like find, but raises ValueError if it is not there | "banana".index("na") → 2 |
rfind(x) | position of the last occurrence | "banana".rfind("na") → 4 |
count(x) | how many times it appears (non-overlapping) | "banana".count("an") → 2 |
startswith(x) | starts with… | "python".startswith("py") → True |
endswith(x) | ends with… | "photo.png".endswith(".png") → True |
name = "photo.png"
print(name.endswith((".png", ".jpg"))) # True (accepts a tuple of options)
print(name.find("x")) # -1 (it is not there)
replace and strip
print("hello world".replace("o", "0")) # hell0 w0rld
print("hello world".replace("o", "0", 1)) # hell0 world (only the first one)
print(" hello ".strip()) # 'hello' removes spaces from both ends
print(" hello ".lstrip()) # 'hello '
print(" hello ".rstrip()) # ' hello'
print("--hello--".strip("-")) # 'hello' it also removes other characters
Remember that none of these methods modifies the original string: they return a new one.
Practice in Split user and domain.