python - Split string based on a regular expression -
i have output of command in tabular form. i'm parsing output result file , storing in string. each element in 1 row separated 1 or more whitespace characters, i'm using regular expressions match 1 or more spaces , split it. however, space being inserted between every element:
>>> str1="a b c d" # spaces irregular >>> str1 'a b c d' >>> str2=re.split("( )+", str1) >>> str2 ['a', ' ', 'b', ' ', 'c', ' ', 'd'] # 1 space element between!!!
is there better way this?
after each split str2
appended list.
by using (
,)
, capturing group, if remove them not have problem.
>>> str1 = "a b c d" >>> re.split(" +", str1) ['a', 'b', 'c', 'd']
however there no need regex, str.split
without delimiter specified split whitespace you. best way in case.
>>> str1.split() ['a', 'b', 'c', 'd']
if wanted regex can use ('\s'
represents whitespace , it's clearer):
>>> re.split("\s+", str1) ['a', 'b', 'c', 'd']
or can find non-whitespace characters
>>> re.findall(r'\s+',str1) ['a', 'b', 'c', 'd']
Comments
Post a Comment