首页 > 解决方案 > 如何在破折号前打印一个单词?

问题描述

我正在制作首府城市的单人猜谜游戏,其中显示国家和首府城市的首字母,用户有 2 次猜测输入正确答案。

在外部 .txt 中,我存储了国家和城市,它们用“-”分隔。以下是它们如何格式化的示例:

英格兰 - 伦敦

法国 - 巴黎

印度 - 新德里

假设第二行是随机选择的,我希望程序输出:

“国家是法国,首都的第一个字母是P。试试猜吧!”

任何帮助,将不胜感激!:)

标签: pythonstringdelimiterhyphen

解决方案


这是我的解决方案。

import re

exp = re.compile(r"(?P<country>\w+)[ ]*-[ ]*(?P<city>\w+)")


def __test(text):
    match = exp.match(text)
    print("The country is {country} and the city is {city}".format(**match.groupdict()))
    
    
__test("England - London")

推荐阅读