<p>简单的解决方案</p>
<pre class="lang-py prettyprint-override"><code>#! /usr/bin/python3
txt = "Hello World"
CharacterToFind = 'W'
for index, character in enumerate(txt):
if character == CharacterToFind:
print(index, character)
break
for index in range(len(txt)):
if txt[index] == CharacterToFind:
print(index, txt[index])
break
if CharacterToFind in txt:
print(CharacterToFind)
</code></pre>
<p>基于功能的解决方案:</p>
<pre class="lang-py prettyprint-override"><code>#! /usr/bin/python3
txt = "Hello World"
CharacterToFind = 'W'
def try_to_find(CharacterToFind, txt):
for index in range(len(txt)):
if txt[index] == CharacterToFind:
return (index, txt[index])
return -1
result = try_to_find(CharacterToFind, txt)
if result:
print(result)
</code></pre>
<p>查找列表中所有匹配项的更复杂的解决方案。也是理解<code>yield</code>的好例子</p>
<pre class="lang-py prettyprint-override"><code>#! /usr/bin/python3
txt = "Hello World"
CharacterToFind = 'o'
def try_to_find_v1(CharacterToFind, txt):
for index in range(len(txt)):
if txt[index] == CharacterToFind:
yield (index, txt[index])
yield -1
results = []
find_gen = try_to_find_v1(CharacterToFind, txt)
while True:
res = next(find_gen)
if res == -1:
break
else:
results.append(res)
print("\nv1")
if len(results) > 0:
print(results)
else:
print(-1)
def try_to_find_v2(CharacterToFind, txt):
for index in range(len(txt)):
if txt[index] == CharacterToFind:
yield (index, txt[index])
results = []
find_gen = try_to_find_v2(CharacterToFind, txt)
while True:
try:
results.append(next(find_gen))
except StopIteration:
break
print("\nv2")
if len(results) > 0:
print(results)
else:
print(-1)
</code></pre>
<p>输出:</p>
<pre><code>v1
[(4, 'o'), (7, 'o')]
v2
[(4, 'o'), (7, 'o')]
</code></pre>