<p>因此,有几件事你忽略了/没有按预期进行,第一件是<a href="https://stackoverflow.com/a/538374/5827215">how iterating over strings in python</a>工作:</p>
<pre><code>tilefwnikos_katalogos = "Christoforos 99111111: Eirini 99556677: Costas 99222222: George 99333333: Panayiotis 99444444: Katerina 96543217"
for check in tilefwnikos_katalogos:
print(check)
#print(repr(check)) #this shows it as you would write it in code ('HI' instead of just HI)
</code></pre>
<p>所以<code>check</code>永远不可能等于您正在检查它的任何东西,并且如果没有<code>else</code>语句,变量<code>arxi</code>永远不会被定义。我假设您打算使用来自用户输入的<code>check</code>,而不是循环中的<code>check</code>,但我不确定您是否需要循环:</p>
<pre><code>tilefwnikos_katalogos = "Christoforos 99111111: Eirini 99556677: Costas 99222222: George 99333333: Panayiotis 99444444: Katerina 96543217"
check=str(input("Give a name: ")) #the str() isn't really necessary, it is already a str.
if check=="Christoforos":
arxi=check.find("Christoforos")
elif check=="Eirini":
arxi=check.find("Eirini")
elif check=="Costas":
arxi=check.find("Costas")
elif check=="George":
arxi=check.find("George")
elif check=="Panayiotis":
arxi=check.find("Panayiotis")
elif check=="Katerina":
arxi=check.find("Katerina")
else: raise NotImplementedError("need a case where input is invalid")
s=check.find(" ",arxi)
arxi=s
y=check.find(":",arxi)
telos=y
apotelesma=tilefwnikos_katalogos[arxi+1:telos]
print(apotelesma)
</code></pre>
<p>但是你也可以看看<code>check</code>是否是<code>tilefwnikos_katalogos</code>的子串,然后处理其他条件:</p>
<pre><code>if check.isalpha() and check in tilefwnikos_katalogos:
# ^ ^ see if check is within the string
# ^ make sure the input is all letters, don't want to accept number as input
arxi=check.find(check)
else:
raise NotImplementedError("need a case where input is invalid")
</code></pre>
<p>尽管这会使<code>C</code>和<code>t</code>的输入给出<code>Cristoforos</code>数字,因为它检索第一次出现的字母。另一种方法,包括循环(但不调用变量<code>check</code>!)将字符串拆分为一个列表:</p>
<pre><code>tilefwnikos_katalogos = "..."
check = input(...)
for entry in tilefwnikos_katalogos.split(":"):
name, number = entry.strip().split(" ")
if check == name:
apotelesma=number
break
else:
raise NotImplementedError("need a case where input is invalid")
</code></pre>
<p>尽管如果您仍要解析字符串,并且可能会多次使用数据,但最好将数据打包到<a href="https://stackoverflow.com/a/36088077/5827215">@BernardMeurer suggested</a>这样的dict中:</p>
<pre><code>data = {}
for entry in tilefwnikos_katalogos.split(":"):
name, number = entry.strip().split(" ")
data[name] = number #maybe use int(number)?
if check in data:
apotelesma = data[check]
else:
raise NotImplementedError("need a case where input is invalid")
</code></pre>