开发者

`strip`ing the results of a split in python

开发者 https://www.devze.com 2022-12-27 17:15 出处:网络
i\'m trying to do something pretty simple: line = \"name:bob\" k, v = line.lower().split(\':\') k = k.strip()

i'm trying to do something pretty simple:

line = "name      :    bob"
k, v = line.lower().split(':')
k = k.strip()
v = v.strip()

is there a way to combine this into one line somehow? i found myself writing this over and over again when making parsers, and sometimes this inv开发者_运维技巧olves way more than just two variables.

i know i can use regexp, but this is simple enough to not really have to require it...


k, v = [x.strip() for x in line.lower().split(':')]


import 're'
k,v = re.split(r'\s*:\s*', line)
line = ':'.join((k,v))


>>> map(str.strip,line.lower().split(":"))
['name', 'bob']


":".join([k, v])
0

精彩评论

暂无评论...
验证码 换一张
取 消