Python 3 字符串切片行为不一致

发布于 2024-09-16 22:26:36 字数 318 浏览 13 评论 0原文

想要一种从字符串中提取年月日的简单方法。 使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尤怨 2024-09-23 22:26:36

使用 [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.

情独悲 2024-09-23 22:26:36

最好的方法是使用 strptime

print( strptime( ..., "%Y%m%d" ) )

The best way to do this is with strptime!

print( strptime( ..., "%Y%m%d" ) )
白日梦 2024-09-23 22:26:36
processdate = "20100818" 
print(processdate[0:4]) # year
print(processdate[4:6]) # month
print(processdate[6:8]) # date 
processdate = "20100818" 
print(processdate[0:4]) # year
print(processdate[4:6]) # month
print(processdate[6:8]) # date 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文