擅长:python、mysql、java
<p>如果您有索引并希望用作输入,那么这也是一个好主意:</p>
<pre><code>def split_by_indices(s, indices):
ends = sorted(indices.values()) # we only need the positions
ends.append(len(s))
substrings = []
start = 0
for end in ends:
substrings.append(s[start:end])
start = end + 1
return substrings
</code></pre>
<p>演示:</p>
<pre><code>>>> split_by_indices('foo1bar2xyz', {'1': 3, '2': 7})
['foo', 'bar', 'xyz']
</code></pre>
<p>这个<em>忽略输入字符串中的任何实际数值,只使用字典<em>中的<code>[3, 7]</code>位置。你知道吗</p>
<p>但是,如果您当前构建<code>{'1': 3, '2': 7}</code>映射只是为了分割字符串,那么只使用正则表达式可能更容易:</p>
<pre><code>import re
split_by_digits = re.compile(r'\d').split
result = split_by_digits(inputstring)
</code></pre>