我想用Python W03*17*65.68*KG*0.2891*CR*1*1N
拆分然后捕获
价值数量为17
值kg为65,68
尝试拆分
myarray = Split(strSearchString, "*")
a = myarray(0)
b = myarray(1)
感谢您的帮助
答案 0 :(得分:6)
split
是字符串本身的一种方法,您可以使用[42]
访问列表的元素,而不是方法调用(42)
doc。尝试:
s = 'W03*17*65.68*KG*0.2891*CR*1*1N'
lst = s.split('*')
qty = lst[1]
weight = lst[2]
weight_unit = lst[3]
您可能还对元组解包感兴趣:
s = 'W03*17*65.68*KG*0.2891*CR*1*1N'
_,qty,weight,weight_unit,_,_,_,_ = s.split('*')
您甚至可以使用slice:
s = 'W03*17*65.68*KG*0.2891*CR*1*1N'
qty,weight,weight_unit = s.split('*')[1:4]
答案 1 :(得分:2)
>>> s = "W03*17*65.68*KG*0.2891*CR*1*1N"
>>> lst = s.split("*")
>>> lst[1]
'17'
>>> lst[2]
'65.68'
答案 2 :(得分:1)
您需要在某个字符串上调用split
方法来拆分它。只使用Split(my_str, "x")
将无效: -
>>> my_str = "Python W03*17*65.68*KG*0.2891*CR*1*1N"
>>> tokens = my_str.split('*')
>>> tokens
['Python W03', '17', '65.68', 'KG', '0.2891', 'CR', '1', '1N']
>>> tokens[1]
'17'
>>> tokens[2]
'65.68'
答案 3 :(得分:0)
import string
myarray = string.split(strSearchString, "*")
qty = myarray[1]
kb = myarray[2]
答案 4 :(得分:0)
>>>s ="W03*17*65.68*KG*0.2891*CR*1*1N"
>>>my_string=s.split("*")[1]
>>> my_string
'17'
>>> my_string=s.split("*")[2]
>>> my_string
'65'
答案 5 :(得分:0)
如果你想将价值数量作为17 Value kg捕获为65.68, 解决问题的一种方法是在拆分字符串后使用字典。
>>> s = 'W03*17*65.68*KG*0.2891*CR*1*1N'
>>> s.split('*')
['W03', '17', '65.68', 'KG', '0.2891', 'CR', '1', '1N']
>>> t = s.split('*')
>>> dict(qty=t[1],kg=t[2])
{'kg': '65.68', 'qty': '17'}
希望它有所帮助。