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
You can use slicing to assign :
for i in content:
s=i.split()
name,scores=s[0],s[1:]
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:
name,*scores=i.split()
source to share
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
source to share
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
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 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 []
source to share