我想用 Python 分割线,W03*17*65.68*KG*0.2891*CR*1*1N
然后将 Value qty 捕获为 17 Value kg as 65,68
尝试拆分
myarray = Split(strSearchString, "*")
a = myarray(0)
b = myarray(1)
谢谢你的帮助
我想用 Python 分割线,W03*17*65.68*KG*0.2891*CR*1*1N
然后将 Value qty 捕获为 17 Value kg as 65,68
尝试拆分
myarray = Split(strSearchString, "*")
a = myarray(0)
b = myarray(1)
谢谢你的帮助
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('*')
你甚至可以使用切片:
s = 'W03*17*65.68*KG*0.2891*CR*1*1N'
qty,weight,weight_unit = s.split('*')[1:4]
>>> s = "W03*17*65.68*KG*0.2891*CR*1*1N"
>>> lst = s.split("*")
>>> lst[1]
'17'
>>> lst[2]
'65.68'
您需要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'
If you'd like to capture Value qty as 17 Value kg as 65.68, one way to solve it is using dictionary after splitting strings.
>>> 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'}
Hope it helps.
>>>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'
import string
myarray = string.split(strSearchString, "*")
qty = myarray[1]
kb = myarray[2]