Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在破折号前打印单词?_Python_String_Delimiter_Hyphen - Fatal编程技术网

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

Python 如何在破折号前打印单词?,python,string,delimiter,hyphen,Python,String,Delimiter,Hyphen,我正在首都做一个单人猜谜游戏,其中显示国家和首都的第一个字母,用户有两次猜谜来输入正确答案 在external.txt文件中,我存储了国家和城市,它们之间用“-”分隔。以下是如何格式化它们的示例: 英格兰-伦敦 法国-巴黎 印度-新德里 假设第二行是随机选择的,我希望程序输出以下内容: “国家是法国,首都的第一个字母是p。试试猜吧!” 任何帮助都将不胜感激!:) 所以随机文本就是所选的文本。然后用“-”将其拆分,创建一个类似于['France','Paris']的列表,然后使用这些变量中的'f'

我正在首都做一个单人猜谜游戏,其中显示国家和首都的第一个字母,用户有两次猜谜来输入正确答案

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

英格兰-伦敦

法国-巴黎

印度-新德里

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

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


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

所以随机文本就是所选的文本。然后用“-”将其拆分,创建一个类似于['France','Paris']的列表,然后使用这些变量中的'f'字符串,但请记住它们是一个列表,因此要访问国家,您需要访问列表索引0,它是列表中的第一项,如随机文本[0]对于单词“Paris”中的第一个字母,您首先访问该单词,如列表中的第二项随机文本[1],然后访问该项目的第一个字符,如随机文本[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","France - Paris","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")
重新导入
exp=重新编译(r“(?P\w+[]*-[]*(?P\w+))
定义测试(文本):
match=exp.match(文本)
打印(“国家为{country},城市为{city}”。格式(**match.groupdict())
__测试(“英格兰-伦敦”)

这是否回答了您的问题?不,不完全是。我只想把破折号前的字印出来。谢谢你的评论!那么,一旦你拆分了字符串,你知道如何为列表编制索引吗?因此,如果给你
[1,2,3,4]
并要求你获取
1
,你就不能在Python中这样做了?拆分一个字符串,然后访问一个单词,其工作方式与您读过的相同吗?