user3514461
user3514461

Reputation: 9

How to a split string into different values?

I have:

file=open("file.txt","r")

and the file is in the form:

apple\red\3 months
pear\green\4 months

how do I split the file so it becomes in the form of a list:

fruit = ['apple', 'pear']
colour = ['red','green']
expire = ['3 months', '4 months']

I have absolutely no idea and would appreciate help. What I have now:

file = open('file.txt','r')
for i in file:
   i.readline()
   i.split('\ ')

don't know it this is right, but have no idea when I've split it into the form of:

apple
red
3 months
pear
green
4 months

How I make the first and every 3th row after that into a list, and the 2:th and every 3th after that and so on.

Upvotes: 0

Views: 157

Answers (6)

Scorpion_God
Scorpion_God

Reputation: 1499

You can use sequence unpacking with the .split() method, and then add each value to their separate list. Note that backslashes are used to escape special sequences, so you have to escape the backslash with a backslash and split on '\\' instead.

>>> line = 'apple\red\3 months'
>>> line = line.split('\\')
>>> line
['apple', 'red', '3 months']
>>> fruit, colour, expire = line
>>> print(fruit, colour, expire)
apple red 3 months

When reading from files you also have to .strip() each line because they have newline characters at the end. Solution:

data = {'fruits': [], 'colours': [], 'expires': []}

with open('file.txt') as f:
    for line in f:
        fruit, colour, expire = line.strip().split('\\')
        data['fruits'].append(fruit)
        data['colours'].append(colour)
        data['expires'].append(expire)

Extendable version:

columns = ['fruits', 'colours', 'expires']
data = {c: [] for c in columns}

with open('file.txt') as f:
    for line in f:
        line = line.strip().split('\\')
        for i, c in enumerate(columns):
            data[c].append(line[i])

Untested one-liner:

with open('file.txt') as f: data = {c: d for c, *d in zip(*(['fruits', 'colours', 'expires']+[line.strip().split('\\') for line in f]))}

Upvotes: 1

locoyou
locoyou

Reputation: 1697

You can split the line and add each part to a list. For example:

fruit = []
colour = []
expire = []

file = open('file.txt','r')
for i in file:
   fruit_, colour_, expire_ = i.split('\\')
   fruit.append(fruit_)
   colour.append(colour_)
   expire.append(expire_)

Upvotes: 3

nik_kgp
nik_kgp

Reputation: 1122

You are going right.

fruit = []
color = []
expire = []
file = open('file.txt','r')
for i in file:
       i.readline()
       f, c, exp = i.split('\\')
       fruit.append(f)
       color.append(c)
       expire.append(exp)

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

Use zip with *:

>>> s = r'''apple\red\3 months
pear\green\4 months'''
>>> zip(*(x.rstrip().split('\\') for x in s.splitlines()))
[('apple', 'pear'), ('red', 'green'), ('3 months', '4 months')]

For a file you can do something like:

with open("file.txt") as f:
    fruit, colour, expire = zip(*(line.rstrip().split('\\') for line in f))

zip returns tuples instead of lists, so you can convert them to lists using list().

Upvotes: 0

user1907906
user1907906

Reputation:

for l in open("i.txt"):
    for m in l.split('\\'):
        print(m.strip())

Upvotes: 0

sshashank124
sshashank124

Reputation: 32189

You can do that as follows:

s = ['apple\red\3 months', 'pear\green\4 months']

fruit = [i[0] for i.split('\\') in s]
colour = [i[1] for i.split('\\') in s]
expire = [i[2] for i.split('\\') in s]

Upvotes: 1

Related Questions