将字符串(从随机行)拆分为两个变量

时间:2018-12-22 22:32:22

标签: python

我正在尝试将随机给出的字符串分成两个变量。尝试使用“ .split”,但无法正常工作。如果可能的话,非常感谢给我一个最简单却有效的方法,因为我还是python的新手。这就是我目前正在使用的...

file = open("CapitalCities.txt","r")
file_contents = file.read()

import random
def generateQuiz():
    with open ("CapitalCities.txt") as f:
        lines = f.readlines()
        print(random.choice(lines))

generateQuiz()

...这是我正在使用的文本文件的某些内容:

Albania-Tirana 
Andorra-Andorra la Vella 
Armenia-Yerevan
Austria-Vienna 
Azerbaijan-Baku 
Belarus-Minsk 
Belgium-Brussels 
Bosnia    and    Herzegovina-Sarajevo       
Bulgaria-Sofia

(编辑:忘了提及。拆分必须以“-”触发。我不知道如何在拆分后删除“-”)

3 个答案:

答案 0 :(得分:0)

如果每一行的格式均为'string1-string2',则应使用.split('-')

In [0]: 'string1-string2'.split('-')
Out[0]: ['string1', 'string2']

答案 1 :(得分:0)

您显然需要根据最终目标进行调整,但现在它向您展示了如何构建子列表的列表,该列表表示由-分隔的每个字符串对,并允许您随机选择一个子列表并将其存储在变量xy中。

import random
def generateQuiz():
    with open("CapitalCities.txt") as f:
        # create a list of sublists; [['Albania', 'Tirana'], ['Andorra', 'Andorra la Vella'], ...,]
        # strip() removes '\n', split('-') returns the sublists
        pairs = [line.strip().split('-') for line in f] 
        # pick a random sublist
        # the '=' will try to unpack the two into x and y
        x, y = random.choice(pairs) 
        print(x, y)

generateQuiz()

答案 2 :(得分:0)

也许这会有所帮助:

import random
def generateQuiz():
    with open ("CapitalCities.txt") as f:
        lines = f.readlines()
        words = random.choice(lines).split('-')
        state = words[0]
        capital = words[1]
        print(state, capital)
generateQuiz()