Python split string

The loop below content

has a list containing an unknown number of lines. each line contains a name followed by a set of numbers, each delimited by a space. I am trying to use split

to put a name and each score in a variable, but I am having problems because each name has a variable sum of points. How can I do this without knowing how many points each name will have?

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



source to share

4 answers

You can use slicing to assign :

for i in content:


At the end you will have a name in a variable name

and a list of points in scores


In python 3, you can use star expressions


for i in content:




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 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:]


replaced by a cleaner and is probably more efficient:

first, *rest = seq




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

Just add some sample code to illustrate someone else who might be interested:

#!/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
        print bowler, scores


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


Would give you an output like this:

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




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


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



All Articles