簡體   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