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

2024-07-02 13:12:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想获取指定关键字“dataplane”后的第一个单词

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

我想得到dataplane后面的单词dp0p1


Tags: output关键字descriptioninterfaces单词globalsetvif
2条回答

假设您不可能有多个关键字,假设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

假设您希望生成多个关键字,假设dataplane应该出现多次,您可以在此处使用re.findall

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

这张照片是:

['dp0p1']

相关问题 更多 >