@@ -20,124 +20,128 @@ All contributions are welcome. You can:
2020## Python Cheatsheet
2121
2222- [ Python Basics] ( #python-basics )
23- - [ Math Operators] ( #math-operators )
24- - [ Data Types] ( #data-types )
25- - [ String Concatenation and Replication] ( #string-concatenation-and-replication )
26- - [ Variables] ( #variables )
27- - [ Comments] ( #comments )
28- - [ The print() Function] ( #the-print-function )
29- - [ The input() Function] ( #the-input-function )
30- - [ The len() Function] ( #the-len-function )
31- - [ The str(), int(), and float() Functions] ( #the-str-int-and-float-functions )
23+ - [ Math Operators] ( #math-operators )
24+ - [ Data Types] ( #data-types )
25+ - [ String Concatenation and Replication] ( #string-concatenation-and-replication )
26+ - [ Variables] ( #variables )
27+ - [ Comments] ( #comments )
28+ - [ The print() Function] ( #the-print-function )
29+ - [ The input() Function] ( #the-input-function )
30+ - [ The len() Function] ( #the-len-function )
31+ - [ The str(), int(), and float() Functions] ( #the-str-int-and-float-functions )
3232- [ Flow Control] ( #flow-control )
33- - [ Comparison Operators] ( #comparison-operators )
34- - [ Boolean Operators] ( #boolean-operators )
35- - [ Mixing Boolean and Comparison Operators] ( #mixing-boolean-and-comparison-operators )
36- - [ if Statements] ( #if-statements )
37- - [ else Statements] ( #else-statements )
38- - [ elif Statements] ( #elif-statements )
39- - [ while Loop Statements] ( #while-loop-statements )
40- - [ break Statements] ( #break-statements )
41- - [ continue Statements] ( #continue-statements )
42- - [ for Loops and the range() Function] ( #for-loops-and-the-range-function )
43- - [ Importing Modules] ( #importing-modules )
44- - [ Ending a Program Early with sys.exit()] ( #ending-a-program-early-with-sysexit )
33+ - [ Comparison Operators] ( #comparison-operators )
34+ - [ Boolean Operators] ( #boolean-operators )
35+ - [ Mixing Boolean and Comparison Operators] ( #mixing-boolean-and-comparison-operators )
36+ - [ if Statements] ( #if-statements )
37+ - [ else Statements] ( #else-statements )
38+ - [ elif Statements] ( #elif-statements )
39+ - [ while Loop Statements] ( #while-loop-statements )
40+ - [ break Statements] ( #break-statements )
41+ - [ continue Statements] ( #continue-statements )
42+ - [ for Loops and the range() Function] ( #for-loops-and-the-range-function )
43+ - [ Importing Modules] ( #importing-modules )
44+ - [ Ending a Program Early with sys.exit()] ( #ending-a-program-early-with-sysexit )
4545- [ Functions] ( #functions )
46- - [ Return Values and return Statements] ( #return-values-and-return-statements )
47- - [ The None Value] ( #the-none-value )
48- - [ Keyword Arguments and print()] ( #keyword-arguments-and-print )
49- - [ Local and Global Scope] ( #local-and-global-scope )
50- - [ The global Statement] ( #the-global-statement )
46+ - [ Return Values and return Statements] ( #return-values-and-return-statements )
47+ - [ The None Value] ( #the-none-value )
48+ - [ Keyword Arguments and print()] ( #keyword-arguments-and-print )
49+ - [ Local and Global Scope] ( #local-and-global-scope )
50+ - [ The global Statement] ( #the-global-statement )
5151- [ Exception Handling] ( #exception-handling )
5252- [ Lists] ( #lists )
53- - [ Getting Individual Values in a List with Indexes] ( #getting-individual-values-in-a-list-with-indexes )
54- - [ Negative Indexes] ( #negative-indexes )
55- - [ Getting Sublists with Slices] ( #getting-sublists-with-slices )
56- - [ Getting a List’s Length with len()] ( #getting-a-list%E2%80%99s-length-with-len )
57- - [ Changing Values in a List with Indexes] ( #changing-values-in-a-list-with-indexes )
58- - [ List Concatenation and List Replication] ( #list-concatenation-and-list-replication )
59- - [ Removing Values from Lists with del Statements] ( #removing-values-from-lists-with-del-statements )
60- - [ Using for Loops with Lists] ( #using-for-loops-with-lists )
61- - [ The in and not in Operators] ( #the-in-and-not-in-operators )
62- - [ The Multiple Assignment Trick] ( #the-multiple-assignment-trick )
63- - [ Augmented Assignment Operators] ( #augmented-assignment-operators )
64- - [ Finding a Value in a List with the index() Method] ( #finding-a-value-in-a-list-with-the-index-method )
65- - [ Adding Values to Lists with the append() and insert() Mthods ] ( #adding-values-to-lists-with-the-append-and-insert-methods )
66- - [ Removing Values from Lists with remove()] ( #removing-values-from-lists-with-remove )
67- - [ Sorting the Values in a List with the sort() Method] ( #sorting-the-values-in-a-list-with-the-sort-method )
68- - [ Tuple Data Type] ( #tuple-data-type )
69- - [ Converting Types with the list() and tuple() Functions] ( #converting-types-with-the-list-and-tuple-functions )
53+ - [ Getting Individual Values in a List with Indexes] ( #getting-individual-values-in-a-list-with-indexes )
54+ - [ Negative Indexes] ( #negative-indexes )
55+ - [ Getting Sublists with Slices] ( #getting-sublists-with-slices )
56+ - [ Getting a List’s Length with len()] ( #getting-a-list%E2%80%99s-length-with-len )
57+ - [ Changing Values in a List with Indexes] ( #changing-values-in-a-list-with-indexes )
58+ - [ List Concatenation and List Replication] ( #list-concatenation-and-list-replication )
59+ - [ Removing Values from Lists with del Statements] ( #removing-values-from-lists-with-del-statements )
60+ - [ Using for Loops with Lists] ( #using-for-loops-with-lists )
61+ - [ The in and not in Operators] ( #the-in-and-not-in-operators )
62+ - [ The Multiple Assignment Trick] ( #the-multiple-assignment-trick )
63+ - [ Augmented Assignment Operators] ( #augmented-assignment-operators )
64+ - [ Finding a Value in a List with the index() Method] ( #finding-a-value-in-a-list-with-the-index-method )
65+ - [ Adding Values to Lists with the append() and insert() Methods ] ( #adding-values-to-lists-with-the-append-and-insert-methods )
66+ - [ Removing Values from Lists with remove()] ( #removing-values-from-lists-with-remove )
67+ - [ Sorting the Values in a List with the sort() Method] ( #sorting-the-values-in-a-list-with-the-sort-method )
68+ - [ Tuple Data Type] ( #tuple-data-type )
69+ - [ Converting Types with the list() and tuple() Functions] ( #converting-types-with-the-list-and-tuple-functions )
7070- [ Dictionaries and Structuring Data] ( #dictionaries-and-structuring-data )
71- - [ The keys(), values(), and items() Methods] ( #the-keys-values-and-items-methods )
72- - [ Checking Whether a Key or Value Exists in a Dictionary] ( #checking-whether-a-key-or-value-exists-in-a-dictionary )
73- - [ The get() Method] ( #the-get-method )
74- - [ The setdefault() Method] ( #the-setdefault-method )
75- - [ Pretty Printing] ( #pretty-printing )
71+ - [ The keys(), values(), and items() Methods] ( #the-keys-values-and-items-methods )
72+ - [ Checking Whether a Key or Value Exists in a Dictionary] ( #checking-whether-a-key-or-value-exists-in-a-dictionary )
73+ - [ The get() Method] ( #the-get-method )
74+ - [ The setdefault() Method] ( #the-setdefault-method )
75+ - [ Pretty Printing] ( #pretty-printing )
7676- [ Manipulating Strings] ( #manipulating-strings )
77- - [ Escape Characters] ( #escape-characters )
78- - [ Raw Strings] ( #raw-strings )
79- - [ Multiline Strings with Triple Quotes] ( #multiline-strings-with-triple-quotes )
80- - [ Indexing and Slicing Strings] ( #indexing-and-slicing-strings )
81- - [ The in and not in Operators with Strings] ( #the-in-and-not-in-operators-with-strings )
82- - [ The upper(), lower(), isupper(), and islower() String Mthods] ( #the-upper-lower-isupper-and-islower-string-methods )
83- - [ The isX String Methods] ( #the-isx-string-methods )
84- - [ The startswith() and endswith() String Methods] ( #the-startswith-and-endswith-string-methods )
85- - [ The join() and split() String Methods] ( #the-join-and-split-string-methods )
86- - [ Justifying Text with rjust(), ljust(), and center()] ( #justifying-text-with-rjust-ljust-and-center )
87- - [ Removing Whitespace with strip(), rstrip(), and lstrip()] ( #removing-whitespace-with-strip-rstrip-and-lstrip )
88- - [ Copying and Pasting Strings with the pyperclip Module] ( #copying-and-pasting-strings-with-the-pyperclip-module )
77+ - [ Escape Characters] ( #escape-characters )
78+ - [ Raw Strings] ( #raw-strings )
79+ - [ Multiline Strings with Triple Quotes] ( #multiline-strings-with-triple-quotes )
80+ - [ Indexing and Slicing Strings] ( #indexing-and-slicing-strings )
81+ - [ The in and not in Operators with Strings] ( #the-in-and-not-in-operators-with-strings )
82+ - [ The upper(), lower(), isupper(), and islower() String Methods] ( #the-upper-lower-isupper-and-islower-string-methods )
83+ - [ The isX String Methods] ( #the-isx-string-methods )
84+ - [ The startswith() and endswith() String Methods] ( #the-startswith-and-endswith-string-methods )
85+ - [ The join() and split() String Methods] ( #the-join-and-split-string-methods )
86+ - [ Justifying Text with rjust(), ljust(), and center()] ( #justifying-text-with-rjust-ljust-and-center )
87+ - [ Removing Whitespace with strip(), rstrip(), and lstrip()] ( #removing-whitespace-with-strip-rstrip-and-lstrip )
88+ - [ Copying and Pasting Strings with the pyperclip Module] ( #copying-and-pasting-strings-with-the-pyperclip-module )
89+ - [ String Formatting] ( #string-formatting )
90+ - [ % operator] ( #operator )
91+ - [ String Formatting (str.format)] ( #string-formatting-strformat )
92+ - [ Formatted String Literals (Python 3.6+)] ( #formatted-string-literals-python-36 )
93+ - [ Template Strings] ( #template-strings )
8994- [ Regular Expressions] ( #regular-expressions )
90- - [ Matching Regex Objects] ( #matching-regex-objects )
91- - [ Grouping with Parentheses] ( #grouping-with-parentheses )
92- - [ Matching Multiple Groups with the Pipe] ( #matching-multiple-groups-with-the-pipe )
93- - [ Optional Matching with the Question Mark] ( #optional-matching-with-the-question-mark )
94- - [ Matching Zero or More with the Star] ( #matching-zero-or-more-with-the-star )
95- - [ Matching One or More with the Plus] ( #matching-one-or-more-with-the-plus )
96- - [ Matching Specific Repetitions with Curly Brackets] ( #matching-specific-repetitions-with-curly-brackets )
97- - [ Greedy and Nongreedy Matching] ( #greedy-and-nongreedy-matching )
98- - [ The findall() Method] ( #the-findall-method )
99- - [ Making Your Own Character Classes] ( #making-your-own-character-classes )
100- - [ The Caret and Dollar Sign Characters] ( #the-caret-and-dollar-sign-characters )
101- - [ The Wildcard Character] ( #the-wildcard-character )
102- - [ Matching Everything with Dot-Star] ( #matching-everything-with-dot-star )
103- - [ Matching Newlines with the Dot Character] ( #matching-newlines-with-the-dot-character )
104- - [ Review of Regex Symbols] ( #review-of-regex-symbols )
105- - [ Case-Insensitive Matching] ( #case-insensitive-matching )
106- - [ Substituting Strings with the sub() Method] ( #substituting-strings-with-the-sub-method )
107- - [ Managing Complex Regexes] ( #managing-complex-regexes )
95+ - [ Matching Regex Objects] ( #matching-regex-objects )
96+ - [ Grouping with Parentheses] ( #grouping-with-parentheses )
97+ - [ Matching Multiple Groups with the Pipe] ( #matching-multiple-groups-with-the-pipe )
98+ - [ Optional Matching with the Question Mark] ( #optional-matching-with-the-question-mark )
99+ - [ Matching Zero or More with the Star] ( #matching-zero-or-more-with-the-star )
100+ - [ Matching One or More with the Plus] ( #matching-one-or-more-with-the-plus )
101+ - [ Matching Specific Repetitions with Curly Brackets] ( #matching-specific-repetitions-with-curly-brackets )
102+ - [ Greedy and Nongreedy Matching] ( #greedy-and-nongreedy-matching )
103+ - [ The findall() Method] ( #the-findall-method )
104+ - [ Making Your Own Character Classes] ( #making-your-own-character-classes )
105+ - [ The Caret and Dollar Sign Characters] ( #the-caret-and-dollar-sign-characters )
106+ - [ The Wildcard Character] ( #the-wildcard-character )
107+ - [ Matching Everything with Dot-Star] ( #matching-everything-with-dot-star )
108+ - [ Matching Newlines with the Dot Character] ( #matching-newlines-with-the-dot-character )
109+ - [ Review of Regex Symbols] ( #review-of-regex-symbols )
110+ - [ Case-Insensitive Matching] ( #case-insensitive-matching )
111+ - [ Substituting Strings with the sub() Method] ( #substituting-strings-with-the-sub-method )
112+ - [ Managing Complex Regexes] ( #managing-complex-regexes )
108113- [ Handling File and Directory Paths] ( #handling-file-and-directory-paths )
109- - [ Backslash on Windows and Forward Slash on OS X and Linux] ( #backslash-on-windows-and-forward-slash-on-os-x-and-linux )
110- - [ The Current Working Directory] ( #the-current-working-directory )
111- - [ Absolute vs. Relative Paths ] ( #absolute-vs-relative-paths )
112- - [ Handling Absolute and Relative Paths] ( #handling- absolute-and -relative-paths )
113- - [ Creating New Folders ] ( #creating-new-folders )
114- - [ Checking Path Validity] ( #checking-path-validity )
115- - [ Finding File Sizes and Folder Contents] ( #finding-file-sizes-and-folder-contents )
116- - [ Copying Files and Folders] ( #copying-files-and-folders )
117- - [ Moving and Renaming Files and Folders] ( #moving-and-renaming-files-and-folders )
118- - [ Permanently Deleting Files and Folders] ( #permanently-deleting-files-and-folders )
119- - [ Safe Deletes with the send2trash Module] ( #safe-deletes-with-the-send2trash-module )
120- - [ Walking a Directory Tree] ( #walking-a-directory-tree )
114+ - [ Backslash on Windows and Forward Slash on OS X and Linux] ( #backslash-on-windows-and-forward-slash-on-os-x-and-linux )
115+ - [ The Current Working Directory] ( #the-current-working-directory )
116+ - [ Creating New Folders ] ( #creating-new-folders )
117+ - [ Absolute vs. Relative Paths] ( #absolute-vs -relative-paths )
118+ - [ Handling Absolute and Relative Paths ] ( #handling-absolute-and-relative-paths )
119+ - [ Checking Path Validity] ( #checking-path-validity )
120+ - [ Finding File Sizes and Folder Contents] ( #finding-file-sizes-and-folder-contents )
121+ - [ Copying Files and Folders] ( #copying-files-and-folders )
122+ - [ Moving and Renaming Files and Folders] ( #moving-and-renaming-files-and-folders )
123+ - [ Permanently Deleting Files and Folders] ( #permanently-deleting-files-and-folders )
124+ - [ Safe Deletes with the send2trash Module] ( #safe-deletes-with-the-send2trash-module )
125+ - [ Walking a Directory Tree] ( #walking-a-directory-tree )
121126- [ Reading and Writing Files] ( #reading-and-writing-files )
122- - [ The File Reading/Writing Process] ( #the-file-readingwriting-process )
123- - [ Opening Files with the open() Function] ( #opening-files-with-the-open-function )
124- - [ Reading the Contents of Files] ( #reading-the-contents-of-files )
125- - [ Writing to Files] ( #writing-to-files )
126- - [ Saving Variables with the shelve Module] ( #saving-variables-with-the-shelve-module )
127- - [ Saving Variables with the pprint.pformat() Function] ( #saving-variables-with-the-pprintpformat-function )
128- - [ Reading ZIP Files] ( #reading-zip-files )
129- - [ Extracting from ZIP Files] ( #extracting-from-zip-files )
130- - [ Creating and Adding to ZIP Files] ( #creating-and-adding-to-zip-files )
127+ - [ The File Reading/Writing Process] ( #the-file-readingwriting-process )
128+ - [ Opening and reading files with the open() function] ( #opening-and-reading-files-with-the-open-function )
129+ - [ Writing to Files] ( #writing-to-files )
130+ - [ Saving Variables with the shelve Module] ( #saving-variables-with-the-shelve-module )
131+ - [ Saving Variables with the pprint.pformat() Function] ( #saving-variables-with-the-pprintpformat-function )
132+ - [ Reading ZIP Files] ( #reading-zip-files )
133+ - [ Extracting from ZIP Files] ( #extracting-from-zip-files )
134+ - [ Creating and Adding to ZIP Files] ( #creating-and-adding-to-zip-files )
131135- [ Debugging] ( #debugging )
132- - [ Raising Exceptions] ( #raising-exceptions )
133- - [ Getting the Traceback as a String] ( #getting-the-traceback-as-a-string )
134- - [ Assertions] ( #assertions )
135- - [ Logging] ( #logging )
136- - [ Logging Levels] ( #logging-levels )
137- - [ Disabling Logging] ( #disabling-logging )
138- - [ Logging to a File] ( #logging-to-a-file )
136+ - [ Raising Exceptions] ( #raising-exceptions )
137+ - [ Getting the Traceback as a String] ( #getting-the-traceback-as-a-string )
138+ - [ Assertions] ( #assertions )
139+ - [ Logging] ( #logging )
140+ - [ Logging Levels] ( #logging-levels )
141+ - [ Disabling Logging] ( #disabling-logging )
142+ - [ Logging to a File] ( #logging-to-a-file )
139143- [ Virtual Environment] ( #virtual-environment )
140- - [ Windows] ( #windows )
144+ - [ Windows] ( #windows )
141145- [ Lambda Functions] ( #lambda-functions )
142146- [ Ternary Conditional Operator] ( #ternary-conditional-operator )
143147
@@ -1614,6 +1618,75 @@ center():
16141618
16151619[ * Return to the Top* ] ( #python-cheatsheet )
16161620
1621+ ## String Formatting
1622+
1623+ ### % operator
1624+
1625+ ``` python
1626+ >> > name = ' Pete'
1627+ >> > ' Hello %s ' % name
1628+ " Hello Pete"
1629+ ```
1630+
1631+ We can use the ` %x ` format specifier to convert an int value to a string:
1632+
1633+ ``` python
1634+ >> > num = 5
1635+ >> > ' I have %x apples' % num
1636+ " I have 5 apples"
1637+ ```
1638+
1639+ [ * Return to the Top* ] ( #python-cheatsheet )
1640+
1641+ ### String Formatting (str.format)
1642+
1643+ Python 3 introduced a new way to do string formatting that was later back-ported to Python 2.7. This makes the syntax for string formatting more regular.
1644+
1645+ ``` python
1646+ >> > name = ' John'
1647+ >> > ' Hello {} ' .format(name)
1648+ ' Hello John'
1649+ ```
1650+
1651+ The official [ Python 3.x documentation] ( https://docs.python.org/3/library/stdtypes.html?highlight=sprintf#printf-style-string-formatting ) recommend ` str.format ` over the ` % ` operator:
1652+
1653+ > The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.
1654+
1655+ [ * Return to the Top* ] ( #python-cheatsheet )
1656+
1657+ ### Formatted String Literals (Python 3.6+)
1658+
1659+ ``` python
1660+ >> > name = ' Elizabeth'
1661+ >> > f ' Hello { name} ! '
1662+ ' Hello Elizabeth!
1663+ ```
1664+
1665+ It is even possible to do inline arithmetic with it:
1666+
1667+ ```python
1668+ >> > a = 5
1669+ >> > b = 10
1670+ >> > f ' Five plus ten is { a + b} and not { 2 * (a + b)} . '
1671+ ' Five plus ten is 15 and not 30.'
1672+ ```
1673+
1674+ [ * Return to the Top* ] ( #python-cheatsheet )
1675+
1676+ ### Template Strings
1677+
1678+ A simpler and less powerful mechanism, but it is recommended when handling format strings generated by users. Due to their reduced complexity template strings are a safer choice.
1679+
1680+ ``` python
1681+ >> > from string import Template
1682+ >> > name = ' Elizabeth'
1683+ >> > t = Template(' Hey $name!' )
1684+ >> > t.substitute(name = name)
1685+ ' Hey Elizabeth!'
1686+ ```
1687+
1688+ [ * Return to the Top* ] ( #python-cheatsheet )
1689+
16171690## Regular Expressions
16181691
161916921 . Import the regex module with import re.
@@ -2058,7 +2131,7 @@ folder names. On Unix based operating system such as macOS, Linux, and BSDs,
20582131the forward slash (/ ) is used as the path separator. Joining paths can be
20592132a headache if your code needs to work on different platforms.
20602133
2061- Fortunately, Python provides easy ways to handle this. We will showcase
2134+ Fortunately, Python provides easy ways to handle this. We will showcase
20622135how to deal with this with both `os.path.join` and `pathlib.Path.joinpath`
20632136
20642137Using `os.path.join` on Windows:
@@ -2205,10 +2278,8 @@ There are two ways to specify a file path.
22052278
22062279There are also the dot (.) and dot- dot (..) folders. These are not real folders but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot- dot”) means “the parent folder.”
22072280
2208-
22092281[* Return to the Top* ](# python-cheatsheet)
22102282
2211-
22122283# ## Handling Absolute and Relative Paths
22132284
22142285To see if a path is an absolute path:
@@ -2418,7 +2489,6 @@ Output (truncated):
24182489 / usr/ bin / idle3
24192490 ...
24202491
2421-
24222492To find the total size of all the files in this directory:
24232493
24242494** WARNING ** : Directories themselves also have a size! So you might want to
@@ -2453,7 +2523,6 @@ Using `pathlib` on \*nix:
24532523
24542524[* Return to the Top* ](# python-cheatsheet)
24552525
2456-
24572526# ## Copying Files and Folders
24582527
24592528The shutil module provides functions for copying files, as well as entire folders.
@@ -2575,6 +2644,7 @@ manually opening it, etc. Check out the
25752644if you want to know more!
25762645
25772646# # Reading and Writing Files
2647+
25782648# ## The File Reading/Writing Process
25792649
25802650To read/ write to a file in Python, you will want to use the `with `
0 commit comments