【问题标题】:Python - can split() command be indexed?Python - 可以为 split() 命令编制索引吗?
【发布时间】:2017-03-27 13:49:43
【问题描述】:

我正在尝试解析和拆分行:

redfish - 12,000 lbs - trade for SNE stocks

我正在尝试的代码是:

elif ('-' in line) and ('lbs' in line):
    fish, remainder = line.split('-')               #splits line into two halves at the - (fish to one side)
    #print("line.split is:", line.split(':'))
    if '@' in remainder:
        weight, price = remainder.split('@')        #splits already split piece (remainder) into two halves at @
        if '-->' in price:
            price, junk = price.split('-->')
    if 'trade' in remainder:
        if 'to ' in remainder:
            weight, price = remainder.split('to ')
        elif ' or ' in remainder:
            weight, price = remainder.split(' or ') #add spaces around ' or ' so we don't match 'for'
    if 'swap' in remainder:
        weight, price = remainder.split('to ')

在线失败:

fish, remainder = line.split('-')

出现错误:

ValueError: too many values to unpack (expected 2)

现在我知道这是因为该行中有 2 个 '-' 并且 Python 不知道要拆分哪个,所以我尝试告诉它在第一个 '-' 上拆分:@ 987654327@ 但失败了。

所以我的问题是:有没有办法解决这个问题?我可以用另一种方式索引split() 命令,以便我可以成功地拆分该行吗?

感谢任何帮助或提示。

【问题讨论】:

    标签: python csv split


    【解决方案1】:

    你很接近,尝试使用:

    line.split('-', 1)

    它告诉它只在遇到的第一个“-”处拆分字符串。

    但是,如果您只想拆分第二个命令,我不知道直接“索引”您的拆分命令的任何可能性。

    在这种情况下,我建议拆分整个字符串,然后加入您想要的部分。

    【讨论】:

    • 哦,明白了。我知道这将是一个简单的答案。是的,我希望稍后当它在其余部分时,我将不得不拆分第二个。不过感谢您的回答:) 我会在几分钟内单击复选标记以接受它
    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 2017-10-29
    • 2020-11-23
    相关资源
    最近更新 更多