python中[:-1]

xiaoxiao2021-02-28  119

python中[:-1]: 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.

a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items >>> seq[:] # [seq[0], seq[1], ..., seq[-1] ] >>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ] >>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]] >>> seq[low:high] # [seq[low], seq[low+1], ..., seq[high-1]] >>> seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ] >>> seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ] >>> seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]] >>> seq[low:high:stride] # [seq[low], seq[low+stride], ..., seq[high-1]]
转载请注明原文地址: https://www.6miu.com/read-69435.html

最新回复(0)