Python 3 string slice behavior inconsistent
Wanted an easy way to extract year month and day from a string. Using Python 3.1.2
Tried this:
processdate = "20100818"
print(开发者_如何学运维processdate[0:4])
print(processdate[4:2])
print(processdate[6:2])
Results in:
...2010
...
...
Reread all the string docs, did some searching, can't figure out why it'd be doing this. I'm sure this is a no brainer that I'm missing somehow, I've just banged my head on this enough today.
With a slice of [4:2], you're telling Python to start at character index 4 and stop at character index 2. Since 4 > 2, you are already past where you should stop when you start, so the slice is empty.
Did you want the fourth and fifth characters? Then you want [4:6] instead.
The best way to do this is with strptime
!
print( strptime( ..., "%Y%m%d" ) )
processdate = "20100818"
print(processdate[0:4]) # year
print(processdate[4:6]) # month
print(processdate[6:8]) # date
精彩评论