Vijay
Vijay

Reputation: 1817

Is there an easy way to remove the white spaces in list items

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

Answers (3)

liweibelieve
liweibelieve

Reputation: 11

>>> word ='SAMPLE TEXT               :HELLO                '
>>> k,v=[str.strip(x) for x in word.split(':')]
>>> k
'SAMPLE TEXT'
>>> v
'HELLO'

Upvotes: 1

fredtantini
fredtantini

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

falsetru
falsetru

Reputation: 369164

Using unbound method str.strip with map:

>>> word ='SAMPLE TEXT               :HELLO                '
>>> k, v = map(str.strip, word.split(':'))
>>> k
'SAMPLE TEXT'
>>> v
'HELLO'

Upvotes: 3

Related Questions