Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split in python

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
like image 940
Albert Avatar asked Oct 21 '25 08:10

Albert


1 Answers

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()
like image 54
Mazdak Avatar answered Oct 22 '25 21:10

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!