0

我有

k= (('answer ', ' Answer the call for a channel(answer )'), ('att_xfer ', ' Attended Transfer(att_xfer )'), ('bind_digit_action ', ' Bind a key sequence or regex to an action.(bind_digit_action )'))

我想去掉所有多余的空格。我怎样才能做到这一点

4

3 回答 3

6

如果您的意思是“额外空格”,则每个字符串开头和结尾的空格:

k = tuple(tuple(b.strip() for b in a) for a in k)

如果要删除字符串中的一些其他“额外空格”(例如(answer )=> (answer)),则必须定义更多规则。

于 2013-01-11T12:37:39.757 回答
3

如果要删除所有空格:

tuple(tuple("".join(i.split()) for i in a) for a in k)

出去:

(('answer', 'Answerthecallforachannel(answer)'),
 ('att_xfer', 'AttendedTransfer(att_xfer)'),
 ('bind_digit_action',
  'Bindakeysequenceorregextoanaction.(bind_digit_action)'))

或者如果您因此不需要元组:

from itertools import chain
["".join(i.split()) for i in chain.from_iterable(k)]

出去:

['answer',
 'Answerthecallforachannel(answer)',
 'att_xfer',
 'AttendedTransfer(att_xfer)',
 'bind_digit_action',
 'Bindakeysequenceorregextoanaction.(bind_digit_action)']
于 2013-01-11T12:45:18.077 回答
1

另一种方法是:

tuple(map(lambda x:tuple(map(lambda y:y.strip(),x)),k))
于 2013-01-11T12:40:59.013 回答