Section | Video Links |
---|---|
Interpreter Overview | |
Interpreter Use Case | |
String Slicing | |
repr Dunder Method |
... Refer to Book or Design Patterns In Python website to read textual content.
... Refer to Book or Design Patterns In Python website to read textual content.
... Refer to Book or Design Patterns In Python website to read textual content.
python ./interpreter/interpreter_concept.py
5 + 4 - 3 + 7 - 2
['5', '+', '4', '-', '3', '+', '7', '-', '2']
11
((((5 Add 4) Subtract 3) Add 7) Subtract 2)
... Refer to Book or Design Patterns In Python website to read textual content.
python ./interpreter/client.py
5 + IV - 3 + VII - 2
['5', '+', 'IV', '-', '3', '+', 'VII', '-', '2']
11
((((5 Add IV(4)) Subtract 3) Add VII(7)) Subtract 2)
Sometimes you want part of a string. In the example code, when I am interpreting the roman numerals, I am comparing the first one or two characters in the context with IV
or CM
or many other roman numeral combinations. If the match is true then I continue with further commands.
The format is
string[start: end: step]
E.g., the string may be
MMMCMXCIX
and I want the first three characters,
test = "MMMCMXCIX"
print(test[0: 3])
Outputs
MMM
or I want the last 4 characters
test = "MMMCMXCIX"
print(test[-4:])
Outputs
XCIX
or I want a section in the middle
test = "MMMCMXCIX"
print(test[2:5])
Outputs
MCM
or stepped
test = "MMMCMXCIX"
print(test[2:9:2])
Outputs
MMCX
or even reversed
test = "MMMCMXCIX"
print(test[::-1])
Outputs
XICXMCMMM
The technique is very common in examples of Python source code throughout the internet. So, when you see the []
with numbers and colons inside, eg, [:-1:]
, it is likely to do with extracting a portion of a data structure.
Note that the technique also works on Lists and Tuples.
test = [1,2,3,4,5,6,7,8,9]
print(test[0: 3])
print(test[-4:])
print(test[2:5])
print(test[2:9:2])
print(test[::-1])
print(test[:-1:])
Outputs
[1, 2, 3]
[6, 7, 8, 9]
[3, 4, 5]
[3, 5, 7, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8]
... Refer to Book or Design Patterns In Python website to read textual content.