They are called in English slices , which mean something like slices. When you count the slices in Python from start to finish, they start at 0 (zero) before of the first character and count between characters to You cover all the slice.
Look at the following image:
In the case of the name you propose,
e s t a 1 s e g 0 8 3 1 a . t x t
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
0 8 <-- mes [8:10]
3 1 <-- día [10:12]
The slice 08
that we will call month is between 8 (which is where the slice begins and the 10 that is where it ends).
The slice 31
that we call day is between 10 (the index before of the character) and 12 (the index after the last character of the slice) ).
What you want, is then, as follows:
fn = 'esta1seg0831a.txt'
estacion = '2016-%s-%s' % (fn[8:10], fn[10:12])
print (estacion)
2016-08-31
As you can see I'm using character substitution in the variable estación
. Use %s
to indicate that the marker should be replaced by the first value found. The second marker is replaced by the second value and so on. There must be an equal number of markers and values to replace them.
You can see how the code runs here: link
Edit
The companion @ jose-hermosilla-rodrigo offers us a more elegant alternative:
fn = 'esta1seg0831a.txt'
estacion = "-".join(["2016", fn[8:10], fn[10:12] ])
print(estacion)
You can see its effectiveness in this link: link