-
-
Notifications
You must be signed in to change notification settings - Fork 522
/
string.py
61 lines (48 loc) · 2.28 KB
/
string.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Strings are an ordered collection of unicode characters that cannot be
modified at runtime. This module shows how strings are created, iterated,
accessed and concatenated.
"""
# Module-level constants
_DELIMITER = " | "
def main():
# Strings are some of the most robust data structures around
content = "Ultimate Python study guide"
# We can compute the length of a string just like all other data structures
assert len(content) > 0
# We can use range slices to get substrings from a string
assert content[:8] == "Ultimate"
assert content[9:15] == "Python"
assert content[::-1] == "ediug yduts nohtyP etamitlU"
# Like tuples, we cannot change the data in a string. However, we can
# create a new string from existing strings
new_content = f"{content.upper()}{_DELIMITER}{content.lower()}"
assert _DELIMITER in new_content
# We can split one string into a list of strings
split_content = new_content.split(_DELIMITER)
assert isinstance(split_content, list)
assert len(split_content) == 2
assert all(isinstance(item, str) for item in split_content)
# A two-element list can be decomposed as two variables
upper_content, lower_content = split_content
assert upper_content.isupper() and lower_content.islower()
# Notice that the data in `upper_content` and `lower_content` exists
# in the `new_content` variable as expected
assert upper_content in new_content
assert new_content.startswith(upper_content)
assert lower_content in new_content
assert new_content.endswith(lower_content)
# Notice that `upper_content` and `lower_content` are smaller in length
# than `new_content` and have the same length as the original `content`
# they were derived from
assert len(upper_content) < len(new_content)
assert len(lower_content) < len(new_content)
assert len(upper_content) == len(lower_content) == len(content)
# We can also join `upper_content` and `lower_content` back into one
# string with the same contents as `new_content`. The `join` method is
# useful for joining an arbitrary amount of text items together
joined_content = _DELIMITER.join(split_content)
assert isinstance(joined_content, str)
assert new_content == joined_content
if __name__ == "__main__":
main()