在关键字后打印第一个单词

时间:2019-10-29 01:42:03

标签: python python-3.x

我想获得指定关键字'dataplane'之后的第一个单词

output = 'set interfaces dataplane dp0p1 vif 2129 description '*** WAN - Global ***''

我想得到数据平面后面的 dp0p1 一词

2 个答案:

答案 0 :(得分:1)

假设您想使用多个关键字,并假设dataplane应该多次出现,则可以在此处使用re.findall

output = 'set interfaces dataplane dp0p1 vif 2129 description '
matches = re.findall('\\bdataplane (\S+)', output)
print(matches)

此打印:

['dp0p1']

答案 1 :(得分:0)

假设您不可能只使用一个关键字,并假设一次dataplane出现一次,则可以在此处使用next

output = 'set interfaces dataplane dp0p1 vif 2129 description'

splitted = output.split()
print(next((y for x, y in zip(splitted, splitted[1:]) if x == 'dataplane'), ''))

此打印:

dp0p1