<p><code>[1:]</code>从列表中获取一个<em>切片</em>,它本身就是一个列表:</p>
<pre><code>>>> remainderforone
['the', 'quick brown fox']
>>> remainderforone[1:]
['quick brown fox']
</code></pre>
<p>这里的切片表示法<code>[1:]</code>表示从索引1(第二项)到列表末尾的所有内容都要切片。列表中只有两项,因此您会得到一个大小为1的列表,因为第一项被跳过</p>
<p>要修复此问题,只需提取列表中的单个元素。我们知道列表应该包含2个元素,所以您需要第二项,所以只需使用索引1:</p>
<pre><code>>>> remainderforone[1]
'quick brown fox'
</code></pre>
<P>作为一个更一般的解决方案,您可能需要考虑使用{a1}:</p>
<pre><code>for s in ['the quick brown fox', 'hi there', 'single', '', 'abc\tefg']:
first, sep, rest = s.partition(' ')
first, sep, rest
('the', ' ', 'quick brown fox')
('hi', ' ', 'there')
('single', '', '')
('', '', '')
('abc\tefg', '', '')
</code></pre>
<p>根据您希望如何处理没有发生分区的情况,您可以返回<code>rest</code>,或者可能返回<code>first</code>:</p>
<pre><code>def whatistheremainder(v):
first, sep, rest = v.partition(' ')
return rest
for s in ['the quick brown fox', 'hi there', 'single', '', 'abc\tefg']:
whatistheremainder(s)
'quick brown fox'
'there'
''
''
''
</code></pre>
<p>或者,您可以争辩说,如果没有分区发生,那么应该返回原始字符串,因为没有要删除的第一个字。如果未发生分区,则可以使用以下事实:<code>sep</code>将是空字符串:</p>
<pre><code>def whatistheremainder(v):
first, sep, rest = v.partition(' ')
return rest if sep else first
for s in ['the quick brown fox', 'hi there', 'single', '', 'abc\tefg']:
whatistheremainder(s)
'quick brown fox'
'there'
'single'
''
'abc\tefg'
</code></pre>