Python中的字符串切割

4
在下面的循环中,content 是一个包含未知数量字符串的列表。每个字符串都包含一个名称和一组数字,每个数字之间用空格分隔。我试图使用split将名称和每个分数放入变量中,但是由于每个名称具有可变数量的分数,所以我遇到了麻烦。如果不知道每个名称将有多少分数,我该如何做到这一点?
for i in content:
    name, score1, score2 = i.split()
    print name, score1, score2
4个回答

8
您可以使用切片赋值
for i in content:
   s=i.split()
   name,scores=s[0],s[1:]

在最后,您将得到name变量中的名称和scores列表。
在Python 3中,您可以使用星号表达式
for i in content:
   name,*scores=i.split()

2

您可以使用扩展可迭代解包

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

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

此内容仅适用于Python 3.x。

对于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

在Python 2.x中,这是一种切片算法。
first, rest = seq[0], seq[1:]

被更清洁、可能更有效的方式所取代:

first, *rest = seq

1
我喜欢@kasra上面的答案,因为它适用于Python 2.x和3.x(还没有足够的积分评论Kasra的帖子)
只是添加一些示例代码,以便其他人可以更好地理解:
#!/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()

有一个输入文件 bowling_scores.txt,内容如下:
John 210 199 287 300 291
Paul 188 165 200
George 177 201
Ringo 255 189 201 300

Yoko 44
Brian

会给您输出如下内容:
John ['210', '199', '287', '300', '291']
Paul ['188', '165', '200']
George ['177', '201']
Ringo ['255', '189', '201', '300']
Yoko ['44']
Brian []

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

split返回一个列表,所以你需要使用索引来获取值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接