如何根据if-else条件将字符串列表切成匹配的字符串索引

时间:2019-07-18 13:17:49

标签: python-3.x string list for-loop if-statement

我有一个字符串列表=

- <Team>
  <id>8</id> 
  <name>OurSupport</name> 
  <uri>/finesse/api/Team/8</uri> 
- <users>
- <User>
  <dialogs>/finesse/api/User/C.person/Dialogs</dialogs> 
  <extension /> 
  <firstName>Caz</firstName> 
  <lastName>Person</lastName> 
  <loginId>C.Person</loginId> 
  <pendingState /> 
  <state>ACTIVE</state> 
  <stateChangeTime>2019-07-15T19:54:40.846Z</stateChangeTime> 
  <uri>/finesse/api/User/C.Person</uri> 
  </User>
  </users>
  </Team>

我想在出现“ note”之后去除所有字符串。 它应该返回

['after','second','shot','take','note','of','the','temp']

还有一些列表没有标志词“ note”。

因此,如果有字符串列表=

['after','second','shot','take']

它应该按原样返回列表。 如何快速做到这一点?我必须对长度不等的许多列表重复同样的事情。

['after','second','shot','take','of','the','temp']

2 个答案:

答案 0 :(得分:2)

切片列表时无需迭代:

strings[:strings.index('note')+1]

其中s是您输入的字符串列表。末尾片是排他的,因此+1确保'note'是一部分。

如果缺少数据('note'):

try:
    final_lst = strings[:strings.index('note')+1]
except ValueError:
    final_lst = strings

答案 1 :(得分:0)

如果您想确保标记的单词存在:


    if 'note' in lst:
        lst = lst[:lst.index('note')+1]

与上述@Austin的答案几乎相同。