问题描述
在我的程序中,输入给出的语句后,我使用了.title()函数。这样,如果有人填写“阿姆斯特丹中央”,我的程序将像“阿姆斯特丹中央”一样将其拾取,但是荷兰有一个名为s-Hertogenbosch的城市,如果用户填写“ s-hertogenbosch中央”,则我的程序将其拾取“ S-Hertogenbosch Central”在某种程度上使我的程序像“ s-Hertogenbosch Central”那样选择它,而不是将“ s”作为Capital。有没有一种方法可以更改.title(),它会一直忽略,直到'-'之后,或者将首字母降低到'-',然后将首字母大写。
def inlezen_beginstation(stations):
while True:
try:
vraag1 = str(input("Wat is je beginstation? ")).title()
if vraag1 in stations and vraag1 != stations[-1]:
print(vraag1)
return vraag1
elif vraag1 in stations and vraag1 == stations[1]:
print(f"{Stations[1]} is geen begin station")
elif vraag1 not in stations:
print(f"station {vraag1} niet gevonden")
else:
print(f"")
except ValueError as h:
print(h)
def inlezen_eindstation(stations,beginstation):
while True:
try:
vraag2 = str(input("Wat is je eindstation ")).title()
if vraag2 in stations:
print(vraag2)
return vraag2
else:
print(f"Deze trein komt niet in {vraag2}")
except ValueError as h:
print(h)
stations = ['Schagen','Heerhugowaard','Alkmaar','Castricum','Zaandam',' Amsterdam Sloterdijk','Amsterdam Centraal','Amsterdam Amstel','Utrecht Centraal','s-Hertogenbosch','Eindhoven','Weert','Roermond','Sittard','Maastricht']
beginstation = inlezen_beginstation(stations)
eindstation = inlezen_eindstation(stations,beginstation)
# omroepen_reis(stations,beginstation,eindstation)
解决方法
我认为使用正则表达式替换(使用替换功能)来检测和纠正这种特殊情况是最容易的
import re
s = "s-hertogenbosch".title()
def repl(matchobj):
return matchobj.group(0)[0:2].lower()+matchobj.group(0)[2].upper()
print(re.sub('S-[a-zA-Z]',repl,s))