Home > Back-end >  Convert this String to a List in Python
Convert this String to a List in Python

Time:04-12

I'm new to Python and I try to convert following txt to two lists, splitting Country from Capital.

Afghanistan | Kabul
Albania | Tirana
Algeria | Algiers
...

I tried:

with open("/FILE.txt") as f:
    lines = f.read().split("| ")

CodePudding user response:

If you have a string like string="Kabul Albania" so use Split

a="Kabul Albania"
print(a.split(" ")) #OUTPUT WILL BE ['Kabul', 'Albania']

CodePudding user response:

You are reading the entire file into one big string, then splitting that on the separator. The result will look something like

lines = ['Afghanistan', 'Kabul\nAlbania', 'Tirana\nAlgeria', 'Algiers']

If you want to split the file into lines, the splitlines function does that.

with open("/FILE.txt") as f:
    lines = f.read().splitlines()

But if you want to split that one list into two lists, perhaps try something like

countries = []
capitals = []
with open("/FILE.txt") as f:
    for line in f:
        country, capital = line.rsplit("\n").split(" | ")
        countries.append(country)
        capitals.append(capital)

A better solution still might be to read the values into a dictionary.

capital = {}
with open("/FILE.txt") as f:
    for line in f:
        country, city = line.rsplit("\n").split(" | ")
        capital[country] = city

As an aside, you almost certainly should not have a data file in the root directory of your OS. This location is reserved for administrative files (or really, in practical terms, just the first level of the directory tree hierarchy).

CodePudding user response:

This should work, you had the first part right just need to add the result to two different list

country = []
capitals = []
with open("FILE.txt", "r") as f:
    for line in f:
        result = line.strip().split("|")
        country.append(result[0].strip())
        capitals.append(result[1].strip())

print(country)
print(capitals)
  • Related