如何在Python中提取第一个字符

时间:2018-11-18 21:30:38

标签: python

下午好, 我遇到了一个问题,我想从输入文件中提取“,”之前的第一个字符并放入新列表中。

我的输入文件,如:

[Afghanistan,Kabul

Albania,Tirana

Andorra,Andorra la Vella

Angola,Luanda

Antigua and Barbuda,St Johns

Argentina,Buenos Aires

Armenia,Yerevan

Australia,Canberra

Austria,Vienna

Azerbaijan,Baku

Bahamas,Nassau

Bahrain,Manama

Bangladesh,Dhaka

Barbados,Bridgetown

Belarus,Minsk

Belgium,Brussels

Belize,Belmopan

Benin,Porto Novo, Cotonou

Bhutan,Thimphu]

我尝试过

with open (inputCc, 'r') as myfile_cc:
     my_string = myfile_cc.readlines()
     Cc = ('\n'.join(my_string))
     print (Cc)
country_list = []
country_list = [i.split(",")[0] for i in Cc]
print (country_list)

但不起作用

1 个答案:

答案 0 :(得分:0)

谢谢大家。我找到了解决问题的方法。

    with open (inputCc, 'r') as myfile_cc:
    lines = myfile_cc.readlines()
    countryList = []                     # countryList

    for line in lines:
        split = line.split(',')                       
        split = [split[0], ','.join(split[1:])]
        countryList.append(split[0])
        capiatalList.append(split[1].strip('\n'))