How do you make a copy of a string with the first and last character removed?
INPUT | OUTPUT |
---|---|
$hello$ |
hello |
How do you make a copy of a string with the first and last character removed?
INPUT | OUTPUT |
---|---|
$hello$ |
hello |
Here is the code to do it
istring[1:-1]
# `istring` represents `input string`
istring = "$hello$"
# `ostring` represents `output string`
ostring = istring[1:-1]
print(ostring)
# storage location labeled `ostring` now contains `hello` without `$`
CHARACTER | $ |
h |
e |
l |
l |
o |
$ |
---|---|---|---|---|---|---|---|
REVERSE INDEX | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
INDEX | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
Note that python always subtracts one from the upper limit of a slice index. Thus...
istring[1:2]
is elements1
through1
(inclusive)
istring[1:3]
is elements1
through2
(inclusive)
istring[1:4]
is elements1
through3
(inclusive)
istring[1:-1]
is elements1
through-2
(inclusive)