擅长:python、mysql、java
<p>根据第二个参数查找“\t”在<code>letters</code>中出现的第一个和最后一个位置</p>
<p>如果第二个参数是<code>True</code>,则找到第一个匹配项并按索引值取出第一个标记。这里,当<code>is_begin == True</code>找到第一次出现的索引并通过<code>line[0:t_ind]</code>取出字符串,其中<code>t_ind</code>是第一次出现的索引。0表示从字符串开始,t_ind表示第一个标记的结束</p>
<p>同样,当<code>is_begin != True</code>找到最后一次出现的索引并通过<code>line[t_ind+1:]</code>取出最后一个标记时,其中<code>t_ind</code>是最后一次出现的索引。但是在这里,我们需要将1添加到t_ind,这样我们就可以从<code>\t</code>之后的最后一个标记的开始开始开始。由于我们需要获取最后一个字符的最后一个标记,因此没有给<code>line[t_ind+1:]</code>提供结束索引。希望这是有意义的</p>
<p>可以使用两个位置参数和</p>
<blockquote>
<p><code>find()</code> method finds the first occurrence of the specified value.</p>
</blockquote>
<p>及</p>
<blockquote>
<p><code>rfind()</code> method finds the last occurrence of the specified value.</p>
</blockquote>
<pre><code>def get_field(line, is_begin):
if is_begin == True:
t_ind = line.find('\t')
return line[0:t_ind]
else:
t_ind = line.rfind('\t')
return line[t_ind+1:]
letters = "abc\tdef\tghi\tjkl"
print(get_field(letters, True))
print(get_field(letters, False))
</code></pre>
<p>输出:</p>
<pre><code>abc
jkl
</code></pre>