使用for loop Python打印

2024-04-25 02:18:27 发布

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

我对Python或任何编程语言都很陌生。我发现使用for循环打印任意文本以及列表中的迭代值很有挑战性。我需要的是用任意文本“shutdown”打印列表的整个第一项,并对新文本“no shutdown”重复相同的操作。另外,我希望能够在两个单独的输出之间插入任何文本语句:请给出建议。这里有更多信息。。在

电流输出:不需要

interface Vlan100
 shut
 no shut
interface Vlan108
 shut
 no shut

预期输出:

首次打印:

^{pr2}$

**这是“无关机”的接口输出

*# Second time printing:*
interface Vlan100
 no shutdown
interface Vlan108
 no shutdown

代码提取,为简洁起见,将其截取。

for i in servicetypes:
<snip>
<snip>
elif "ipv4 address" in i or "ipv4 address 8" in i or " ipv4 address 213" in i:
    i = re.sub(r'encapsulation dot1Q \d+\n\s','',i)
    i = re.sub(r'TenGigE[0-9]/[0-9]/[0-9]/[0-9].','Vlan',i)
    internet = i.split("\n")
    print internet[1]
    print " shut"
    print " no shut"

Tags: ornoin文本列表foraddresssnip
2条回答

好吧,有几个错误。1) Python数组的索引位置为0。因此对print internet[1]的调用正在打印数组的第二个元素。如果您在描述中声称“我需要打印列表的第一项”,那么这个调用应该是print internet[0]

其次,您声称需要打印字符串“shutdown”或“no shutdown”。。。但你却在打印“关闭”和“不关闭”。将这些打印语句更改为使用“shutdown”和“no shutdown”。在

此外,您需要设置一些条件来确定是打印字符串“shutdown”还是“no shutdown”;现在您正在打印这两个字符串。在

当前您要执行以下操作:

print " shut"
print " no shut"

其结果是:

^{pr2}$

一如预期。如果您希望它在关闭时打印“关闭”,而不关闭时打印“不关闭”,则需要进行测试:

if shutdown(interface):
    print "shut"
else:
    print "no shut"

或者类似的东西。在


(编辑:好吧,你的回答是,你想要的是上面的,而不是下面的,所以忽略这一部分。在

但是,如果你只想打印

interface Vlan100
 shut
interface Vlan108
 shut
interface Vlan100
 no shut
interface Vlan108
 no shut

然后你需要两个独立的循环。在

不过,目前还不清楚你想要什么,或者你想做什么。)

好吧。以下是如何获得输出:

for what in (" shut", " no shut"):
    for iface in ('vlan100', 'vlan108'):
         print "interface", iface
         print what

相关问题 更多 >