[:-1] 在 python 中是什么意思/做什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15535205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:20:28  来源:igfitidea点击:

What does [:-1] mean/do in python?

python

提问by Matt.

Working on a python assignment and was curious as to what [:-1] means in the context of the following code: instructions = f.readline()[:-1]

正在处理 Python 任务,并且很好奇 [:-1] 在以下代码的上下文中的含义: instructions = f.readline()[:-1]

Have searched on here on S.O. and on Google but to no avail. Would love an explanation!

在 SO 和 Google 上搜索过这里,但无济于事。想要一个解释!

采纳答案by Martijn Pieters

It slices the string to omit the last character, in this case a newline character:

它对字符串进行切片以省略最后一个字符,在本例中为换行符:

>>> 'test\n'[:-1]
'test'

Since this works even on empty strings, it's a pretty safe way of removing that last character, if present:

由于这甚至适用于空字符串,因此删除最后一个字符(如果存在)是一种非常安全的方法:

>>> ''[:-1]
''

This works on any sequence, not just strings.

这适用于任何序列,而不仅仅是字符串。

For lines in a text file, I'd actually use line.rstrip('\n')to only remove a newline; sometimes the last line in the file doesn't end in a newline character and using slicing then removes whatever other character is last on that line.

在文本文件中的行,我实际使用line.rstrip('\n')只删除一个换行符; 有时文件中的最后一行不会以换行符结尾,然后使用切片删除该行最后一行的任何其他字符。

回答by Kartik

It gets all the elements from the list (or characters from a string) but the last element.

它获取列表中的所有元素(或字符串中的字符),但最后一个元素。

:represents going through the list -1implies the last element of the list

:表示遍历列表-1意味着列表 的最后一个元素

回答by Fredrik Pihl

It selects all but the last element of a sequence.

它选择序列中除最后一个元素之外的所有元素。

Example below using a list:

下面使用列表的示例:

In [15]: a=range(10)

In [16]: a
Out[16]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [17]: a[:-1]
Out[17]: [0, 1, 2, 3, 4, 5, 6, 7, 8]

回答by Pavel Anossov

It means "all elements of the sequence but the last". In the context of f.readline()[:-1]it means "I'm pretty sure that line ends with a newline and I want to strip it".

它的意思是“序列的所有元素,但最后一个”。在f.readline()[:-1]它的上下文中意味着“我很确定该行以换行符结尾,我想删除它”。