Python 3 字符串切片行为不一致
想要一种从字符串中提取年月日的简单方法。 使用Python 3.1.2
尝试了这个:
processdate = "20100818"
print(processdate[0:4])
print(processdate[4:2])
print(processdate[6:2])
结果:
...2010
...
...
重新阅读所有字符串文档,做了一些搜索,无法弄清楚为什么要这样做。 我确信这是一个理所当然的事情,我不知何故错过了,今天我已经在这件事上碰了很多脑筋了。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 [4:2] 切片,您可以告诉 Python 从字符索引 4 开始并在字符索引 2 处停止。由于 4 > > 2、开始时已经过了应该停止的地方,所以切片是空的。
你想要第四个和第五个角色吗?那么你需要[4:6]。
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.
最好的方法是使用
strptime
!The best way to do this is with
strptime
!