4

In the loop below, content is a list containing an unknown amount of strings. each string contains a name with a set of numbers after the name, each delimited by a space. I am trying to use split to put the name and each score into a variable but I am having trouble because each name has a variable amount of scores. How would I be able to do this without knowing how many scores each name will have?

for i in content:
    name, score1, score2 = i.split()
    print name, score1, score2
0

4 Answers 4

8

You can use slicing for assignment :

for i in content:
   s=i.split()
   name,scores=s[0],s[1:]

At the end you'll have the name in name variable and list of scores in scores.

In python 3 you can use star expressions :

for i in content:
   name,*scores=i.split()
Sign up to request clarification or add additional context in comments.

Comments

2

You can use Extended Iterable Unpacking

content = ['this 3 5 2', 'that 3 5']

for i in content:
    name, *score = i.split()
    print(name, score)

This is Python 3.x compatible only.

For Python 2.x,

content = ['this 3 5 2', 'that 3 5']

for i in content:
    splitted_content = i.split()
    name, dynamic_score = splitted_content[0], splitted_content[1:]
    print name, dynamic_score

This slicing algorithm in Python 2.x

first, rest = seq[0], seq[1:]

is replaced by the cleaner and probably more efficient:

first, *rest = seq

Comments

1

I like @kasra's answer above because it works for Python 2.x and 3.x (not enough points yet to comment on Kasra's post)

Just adding in some sample code to illustrate for anyone else who might be wondering:

#!/usr/bin/env python
# coding: utf-8

fi = open('bowling_scores.txt','r')

for line in fi:
    if len(line) > 1:       #skip blank rows
        rec=line.split(' ') #subst any delimiter, or just use split() for space
        bowler,scores=rec[0],rec[1:]
        print bowler, scores
fi.close()

With an input file bowling_scores.txt like this:

John 210 199 287 300 291
Paul 188 165 200
George 177 201
Ringo 255 189 201 300

Yoko 44
Brian

Would give you output like this:

John ['210', '199', '287', '300', '291']
Paul ['188', '165', '200']
George ['177', '201']
Ringo ['255', '189', '201', '300']
Yoko ['44']
Brian []

Comments

0
for i in content:
    print i.split(" ")[0],i.split(" ")[1],i.split(" ")[2]

split returns a list, so you have to index to get the values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.