'Convert this String to a List in Python
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("| ")
Solution 1:[1]
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.rstrip("\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.rstrip("\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).
Solution 2:[2]
If you have a string like string="Kabul Albania" so use Split
a="Kabul Albania"
print(a.split(" ")) #OUTPUT WILL BE ['Kabul', 'Albania']
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sid |
Solution 3 | Wessel201 |