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!')
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])
所以随机文本就是选择的文本。然后用“-”将其拆分,创建一个类似于['France','Paris']的列表,然后使用这些变量中的'f'字符串,但请记住它们是一个列表,因此要访问国家,您需要访问列表索引0,它是列表中的第一项,如随机文本[0]对于单词“Paris”中的第一个字母,您首先访问该单词,如列表中的第二项随机文本[1],然后访问该项目的第一个字符,如随机文本[1][0],并将其打印出来
因为你知道你的数据是什么样子的(XXX-YYY),一个简单的破折号和空格分割就可以了:
使用split(),它在输出字符串时非常有用。 守则:
如果要打印随机国家/地区及其首都城市,则需要导入随机
以后可以将更多元素添加到城市列表中
相关问题 更多 >
编程相关推荐