python - Concise way to split a string into a list of fixed number of tokens -
i writing piece of code needs split hyphen delimited string @ 3 tokens. if there less 3 tokens after splitting, should append sufficient number of empty strings in order make 3 tokens.
for example, 'foo-bar-baz'
should split ['foo', 'bar', 'baz']
, foo-bar
should split ['foo', 'bar', '']
.
here code wrote.
def three_tokens(s): tokens = s.split('-', 2) if len(tokens) == 1: tokens.append('') tokens.append('') elif len(tokens) == 2: tokens.append('') return tokens print(three_tokens('')) print(three_tokens('foo')) print(three_tokens('foo-bar')) print(three_tokens('foo-bar-baz')) print(three_tokens('foo-bar-baz-qux'))
here output:
['', '', ''] ['foo', '', ''] ['foo', 'bar', ''] ['foo', 'bar', 'baz'] ['foo', 'bar', 'baz-qux']
my question three_tokens
function have written seems verbose little task. there pythonic way write this, or there python function or class meant kind of task makes code more concise?
you use simple while
loop:
def three_tokens(s): tokens = s.split('-', 2) while len(tokens) < 3: tokens.append('') return tokens
or extend list calculated number of empty strings:
def three_tokens(s): tokens = s.split('-', 2) tokens.extend([''] * (3 - len(tokens))) return tokens
or use concatenation can put in return statement:
def three_tokens(s): tokens = s.split('-', 2) return tokens + [''] * (3 - len(tokens))
Comments
Post a Comment