UglyNerd
UglyNerd

Reputation: 1

Split line in Python 2.7

I want to split line with Python W03*17*65.68*KG*0.2891*CR*1*1N and then capture Value qty as 17 Value kg as 65,68

Tried with split

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

Thanks for your help

Upvotes: 0

Views: 11428

Answers (6)

Vishal Aglawe
Vishal Aglawe

Reputation: 3

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

Upvotes: 0

SamuraiT
SamuraiT

Reputation: 1012

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.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213193

You need to invoke split method on a certain string to split it. Just using Split(my_str, "x") won't work: -

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

Upvotes: 1

phihag
phihag

Reputation: 287755

split is a method of the string itself, and you can access elements of a list with [42], not the method call (42)doc. Try:

s = 'W03*17*65.68*KG*0.2891*CR*1*1N'
lst = s.split('*')
qty = lst[1]
weight = lst[2]
weight_unit = lst[3]

You may also be interested in tuple unpacking:

s = 'W03*17*65.68*KG*0.2891*CR*1*1N'
_,qty,weight,weight_unit,_,_,_,_ = s.split('*')

You can even use a slice:

s = 'W03*17*65.68*KG*0.2891*CR*1*1N'
qty,weight,weight_unit = s.split('*')[1:4]

Upvotes: 6

Pattapong J
Pattapong J

Reputation: 1224

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

Upvotes: 0

applicative_functor
applicative_functor

Reputation: 4976

>>> s = "W03*17*65.68*KG*0.2891*CR*1*1N"
>>> lst = s.split("*")
>>> lst[1]
'17'
>>> lst[2]
'65.68'

Upvotes: 2

Related Questions