Reputation: 1817
I;m trying to split a string using a delimiter and store them in the form of dictionary.
When i use split, it returns a list in which there are white spaces.
I would like to know if we can remove white spaces during the split operation itself or should i have to do something like below to get rid of the white spaces?
the code that i have written is as follows:
word ='SAMPLE TEXT :HELLO '
k,v = words.split(':')
k = k.strip()
v = v.strip()
D[k] = v
kindly let me know
Upvotes: 1
Views: 82
Reputation: 11
>>> word ='SAMPLE TEXT :HELLO '
>>> k,v=[str.strip(x) for x in word.split(':')]
>>> k
'SAMPLE TEXT'
>>> v
'HELLO'
Upvotes: 1
Reputation: 16556
Alternatively, you could use re.split
:
>>> word ='SAMPLE TEXT :HELLO '
>>> import re
>>> k,v = re.split('\s*:\s*',word.strip())
>>> k,v
('SAMPLE TEXT', 'HELLO')
Upvotes: 1