【问题标题】:In python s[:1] first one is ignored but s[:3] in this the third alphabet is included? s is a string在 python s[:1] 中,第一个被忽略,但是 s[:3] 在这个第三个字母表中包含? s 是一个字符串
【发布时间】:2017-07-11 11:00:49
【问题描述】:

为什么在python中切片字符串时假设s='hello'我们运行命令s[1:],结果是'ello'。忽略第一个字母。但是s[:3]给出结果'hel'。第三个字母应该被忽略吗?

【问题讨论】:

标签: python python-2.7 python-3.x


【解决方案1】:

这是切片符号。第一个索引是包含,最后一个索引是排除

当您执行[1:] 时,第一个字母不会被忽略。第一个字母的索引为 0,因此您从字面上告诉符号包括从第二个字母到结尾的所有内容。当您执行[:3] 时,包括索引 0、1 和 2(对应于 h、e、l)。不包括第四个字母(索引 3)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-04
    • 2022-08-23
    • 2012-10-26
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2023-04-02
    • 2016-09-27
    相关资源
    最近更新 更多