您如何在破折号前打印单词?

问题描述

我正在首都进行一个单人猜谜游戏,其中显示了国家和首都的首字母,并且用户有2个猜测来输入正确的答案。

一个外部.txt中,我存储了国家和城市,它们之间用'-'分隔。这是一个如何格式化的示例:

英国-伦敦

法国-巴黎

印度-新德里

说第二行是随机选择的,我希望程序输出以下内容

“国家是法国,首都的首字母是P。尝试猜测!”

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

解决方法

因此,随机文本是所选文本。然后,将其用'-'分割,并创建一个类似于[[France],'Paris']的列表,然后使用在这些变量中输入的'f'字符串,但要记住它们是一个列表,因此可以访问您所在的国家/地区需要访问列表索引0,它是单词'Paris'中第一个字母的列表首项,例如random_text [0],您首先访问单词random_text [1],它是列表中的第二项,然后访问该项目的第一个字符,例如random_text [1] [0]并打印出来

random_text = 'France - Paris'
random_text = random_text.split(' - ')
print(f'The country is {random_text[0]} and the first letter of the capital city is {random_text[1][0]}. Try and guess!')
,

因为您知道数据是什么样的(XXX-YYY),所以只需用破折号和空格分隔即可:

selected = "England - London"
country,city = selected.split(" - ")
print(f"The country is {country} and the city is {city}")
,

使用split。(),它在分隔字符串中非常有用。 代码:

city = ["England - London","France - Paris","India - New Dehli"]
random_guess = city.split(' - ')

如果要打印随机国家或首都,则需要导入随机

import random
city = ["England - London","India - New Dehli"]
random_guess = random.choice(city).split(' - ')
print("The country is",random_guess[0],"and the first letter of the capital city 
is",random_guess[1][0])

您以后可以在城市列表中添加更多元素。

,

这是我的解决方法。

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")