【问题标题】:What is the meaning of "[:-2]" in "header_text = f.read(header_text_size)[:-2].decode('utf-16').encode('utf-8') " [duplicate]“header_text = f.read(header_text_size)[:-2].decode('utf-16').encode('utf-8')”中的“[:-2]”是什么意思 [重复]
【发布时间】:2015-04-23 23:41:14
【问题描述】:
header_text = f.read(header_text_size)[:-2].decode('utf-16').encode('utf-8')

在这段 Python 代码中[:-2] 的含义是什么?我想把它翻译成 Java,我需要知道它的作用。

【问题讨论】:

    标签: java python utf-8 slice


    【解决方案1】:

    a_list[:-2] 从列表 a_list 中删除最后 2 个元素。 a_string[:-2] 从字符串 a_string 中删除最后 2 个字符(可能是您的情况):

    >>> s = 'some string with last chars 012'
    >>> s[:-2]
    'some string with last chars 0'
    

    【讨论】:

      【解决方案2】:

      从序列中切片,第一个元素(包括)到第二个到最后一个(不包括)。

      例如:

      x = [0, 1, 2, 3, 4, 5]
      y = x[:-2]
      print(y)  # [0, 1, 2, 3]
      

      切片始终包含“start”参数,不包括“stop”参数。

      此外,切片的负索引始终表示从末尾向后计数。 (-1 表示最后一个索引,-2 表示倒数第二个等)。

      More on slice notation

      【讨论】:

      • “print(y)”的结果是否正确?为什么与您对@wookie919 的回答结果不同?
      • @feemung 看起来 Tigerhawk 帮我弄错了,抱歉。
      • 没关系,祝你好运。
      猜你喜欢
      • 2020-06-03
      • 1970-01-01
      • 2011-09-23
      • 2016-02-24
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 2012-07-04
      • 2018-01-19
      相关资源
      最近更新 更多