forked from huangsam/ultimate-python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.py
More file actions
Latest commit
61 lines (48 loc) · 2.29 KB
/
Copy pathstring.py
File metadata and controls
61 lines (48 loc) · 2.29 KB
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=" | "
defmain() ->None:
# 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
assertlen(content) >0
# We can use range slices to get substrings from a string
assertcontent[:8] =="Ultimate"
assertcontent[9:15] =="Python"
assertcontent[::-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_DELIMITERinnew_content
# We can split one string into a list of strings
split_content=new_content.split(_DELIMITER)
assertisinstance(split_content, list)
assertlen(split_content) ==2
assertall(isinstance(item, str) foriteminsplit_content)
# A two-element list can be decomposed as two variables
upper_content, lower_content=split_content
assertupper_content.isupper() andlower_content.islower()
# Notice that the data in `upper_content` and `lower_content` exists
# in the `new_content` variable as expected
assertupper_contentinnew_content
assertnew_content.startswith(upper_content)
assertlower_contentinnew_content
assertnew_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
assertlen(upper_content) <len(new_content)
assertlen(lower_content) <len(new_content)
assertlen(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)
assertisinstance(joined_content, str)
assertnew_content==joined_content
if__name__=="__main__":
main()