首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拆分字符串ValueError:需要超过一个值才能解压缩

拆分字符串ValueError:需要超过一个值才能解压缩
EN

Stack Overflow用户
提问于 2015-09-30 04:53:03
回答 2查看 639关注 0票数 1

我正在尝试拆分字符串,我得到了ValueError:需要一个以上的值来解压缩

我想我明白了,为什么会发生这个错误,它之所以发生,是因为没有分拆的价值,对吗?

基本上,我有for循环,它从xml返回字符串。

代码语言:javascript
复制
for channel in tree.findall("channel"):
    title = channel.find('title').text
    channelname,tvguide = title.split("[")
    print(channelname,tvguide)

当我打印标题时,我有这样的内容:

BeIN体育1HD 07:00 - 07:30 + 106.8分钟自动拨号

BeIN体育2HD ValueError发生在这里?

BeIN体育3HD 23:00 - 02:00 + 1216.8分钟都灵足球对美国帕勒莫-意大利联赛(意甲)

BeIN体育4 4HD ValueError发生在这里?

BeIN体育5HD 05:30-07:15+ 91.8分钟马赛对安格斯-法国甲级联赛2015 - 2016周7

我的问题是,如果有些字符串不包含tvguide,我如何才能修复for循环,以便将所有标题拆分为channelname & tvguide?

例如,在没有电视指南的频道(在本例中,BeIN体育2HD,BeIN体育4HD),它应该使tvguide =“”或类似的内容。

伙计们有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-30 05:03:58

与其分别分配信道名称和tvguide,不如使用split方法返回的列表进行工作。

代码语言:javascript
复制
for channel in tree.findall("channel"):
    title = channel.find('title').text
    description = title.split("[")
    print description

这样,您就不必担心通道是否有名称或tvguide,但请确保在通道对象中获得字符串。

as Jon Clements suggested, we still need to figure out if its allowed to access description[1] and as he suggested an elegant way to do is str.partition

代码语言:javascript
复制
for channel in tree.findall("channel"):
    title = channel.find('title').text
    description = title.partition("[") # you get a tuple with three elements head, separator and tail. 
    #head is the portion before the separator, separator itself and tail the rest of the portion of the string
    print description
票数 1
EN

Stack Overflow用户

发布于 2015-09-30 05:08:48

您可以使用简单的if else

代码语言:javascript
复制
x="BeIN Sports 1HD [07:00 - 07:30] + 106.8 min Auto Mundial"

y="BeIN Sports 2H"
ll=[]
ll.append(x)
ll.append(y)
final = [(i,"") if "[" not in i else i.split("[") for i in ll]
print final

输出:[['BeIN Sports 1HD ', '07:00 - 07:30] + 106.8 min Auto Mundial'], ('BeIN Sports 2H', '')]

现在,您可以根据需要轻松地处理列表中的这些元组。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32858053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档