2012-11-17 66 views
0

我想使用Python W03*17*65.68*KG*0.2891*CR*1*1N線拆分,然後捕獲 值數量爲17 價值公斤爲65,68分割線2.7

與分裂

myarray = Split(strSearchString, "*") 
a = myarray(0) 
b = myarray(1) 

感謝您的幫助

嘗試

回答

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' 
+0

'split()'中'r'的用法是什麼? –

+0

@AshwiniChaudhary ..其實這是不需要的。只是測試它。我認爲這是一個'原始字符串'。 –

2
>>> s = "W03*17*65.68*KG*0.2891*CR*1*1N" 
>>> lst = s.split("*") 
>>> lst[1] 
'17' 
>>> lst[2] 
'65.68' 
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] 
+0

我覺得'qty,weight,weight_unit = s.split('*')[1:4]'看起來更好。 –

+0

@AshwiniChaudhary謝謝,還補充說。我推測下一個版本最有可能還要處理額外的值;) – phihag

+0

@AshwiniChaudhary另一種可能的使用切片的方式是:'qty,weight,weight_unit,rest = s.split('*',4)[1 :])'我想在3.x中你可以''qty,weight,weight_unit,* rest = s.split('*')[1:]' –

0
import string 
myarray = string.split(strSearchString, "*") 
qty = myarray[1] 
kb = myarray[2] 
+3

'字符串模塊的使用已被棄用。改用字符串方法。 – Keith

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' 

0

如果你想獲取價值的數量價值17公斤爲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'} 

希望它有幫助。