A convenient slicing function when cutting a character string in Python.
I used to specify the characters to cut out, but many of the explanations didn't come to my mind.
Here, I will post my own interpretation.
# Slice ``` []` `
```python
str_1 = 'python'
print(str_1[2:6])
# 'thon'
For example, if you want to extract only the thon
of the string'python'
, you can use slices and specify [2: 6]
, which is a very convenient function.
However, I feel uncomfortable with the method of setting the numbers here.
This is because the slice is specified by [Start position: End position], but the start position is the number counting the character string from 0, and the end position is the number counting the character string from 1. I don't think it's going to happen once you get used to it, but it doesn't feel right at all.
The following is what I rewrote according to my own interpretation.
str_1 = 'python'
start = 2
count = 4
print(str_1[start:start+count])
# 'thon'
First, specify from which character to count with start
.
Since t
is the second character counting from 0, specify 2
.
Next, specify how many characters you want to retrieve from the start position with count
.
Since 'thon'
is 4 characters, specify 4
.
Slices are interpreted this way.
[(Start position): (Start position + number of characters)]
Specify it with [start: start + count]
on the program.
This is synonymous with the case specified by [2: 6]
, but I think it is a nice explanation.
When you actually write a program, I don't think you need to write it in such a roundabout way. However, you can reduce mistakes by remembering when you are unsure of the specified method. I don't know how the slice was developed, so I don't know, but it would be nice if it was developed with the idea described here. .. ..
Recommended Posts