Python - split() 命令可以被索引吗?

标签 python csv split

我正在尝试解析并分割该行:

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 ')

线路失败:

鱼,余数 = line.split('-')

错误:

ValueError:无法解包的值太多(预计为 2 个)

现在我知道这是因为该行中有 2 个 '-' 而 Python 不知道要拆分到哪一个,所以我尝试告诉它在第一个 '-' 为: fish,remains = line.split('-'[0]) 但失败了。

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

感谢您的帮助或提示。

最佳答案

您已经很接近了,请尝试使用:

line.split('-', 1)

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

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

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

关于Python - split() 命令可以被索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048281/

相关文章:

Python 单元测试所有测试用例

python - NamedTemporaryFile 存在,但外部程序无法访问它

python - django中的日期时间显示和时区转换

python - 从 Django Rest Framework 中的 Json 字符串中删除反斜杠

mysql - 如何将 CSV 文件导入 MySQL 表?

Javascript 使用正则表达式拆分字符串,然后加入它

mysql - 将分割字符串与 mysql 表连接

php - 如何使用php将csv文件上传到mysql?

tsql - 将多行转换为一行,并以逗号作为分隔符

Javascript 拆分、替换表现奇怪