Hello i'm looking for solution to solve my problem:
I have text file countries-and-capitals.txt with example words:
Poland | Warsaw
Sri Lanka | Colombo
and i need to write code that will pick a random name of Country or Capital.
My problem is that i can't figure out how to pick in example Sri Lanka without "|" separator and without Colombo word.
I've stuck on
import random
word = random.choice(open("countries-and-capitals.txt").readlines())
but this code picks whole line with "\n".
CodePudding user response:
You can use list unpacking as well as .split() to handle this in one line:
import random
file = open("countries-and-capitals.txt")
[country, capital] = random.choice(file.readlines()).split(" | ")
file.close()
CodePudding user response:
Let's say you want to pick Sri Lanka:
import random
word = random.choice(open("countries-and-capitals.txt").readlines())
word = word.split(" | ")
country = 'Sri Lanka'
if word[0] == country:
print("Sri Lanka's capital is: " word[1].strip())
You can use split("|") to remove |, and .strip() to remove \n.
Output:
If you want to just print random country or capital, you can apply another random generator:
import random
word = random.choice(open("countries-and-capitals.txt").readlines())
word = word.split(" | ") #remove |
word[1] = word[1].strip() #remove \n
print(random.sample(word, 1)[0])
Output:
CodePudding user response:
Thanks to Ka-Wa Yip BrokenBenchmark Devang Sanghani
With you guys i've found solution to pick randomly: country or capital
import random
word = random.choice(open("countries-and-capitals.txt").readlines())
word = word.strip('\n').split(" | ")
word = random.choice(word[0:2])
print(word)
Thanks !


