繁体   English   中英

Python在元组中的空格

[英]python strip spaces in tuple

我有

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 )'))

我要去除所有多余的空间。 我怎样才能做到这一点

如果您的意思是“多余的空格”,则在每个字符串的开头和结尾分别是:

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

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

如果要删除所有空格:

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)']

另一种方式是这样的:

tuple(map(lambda x:tuple(map(lambda y:y.strip(),x)),k))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM