开发者

Python 3 string slice behavior inconsistent

开发者 https://www.devze.com 2023-01-13 17:46 出处:网络
Wanted an easy way to extract year month and day from a string. Using Python 3.1.2 Tried this: processdate = \"20100818\"

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 
0

精彩评论

暂无评论...
验证码 换一张
取 消