带有城市名称“ s-Hertogenbosch”的python title函数

问题描述

在我的程序中,输入给出的语句后,我使用了.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))

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...