我正在尝试解析并分割该行:
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/