使用for循环打印 - Python

时间:2010-12-17 14:05:09

标签: python

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

当前输出:不需要

interface Vlan100
 shut
 no shut
interface Vlan108
 shut
 no shut

预期输出:

#首次打印:

********* THIS IS INTERFACE OUTPUT WITH "SHUTDOWN" **********
interface Vlan100
 shutdown
interface Vlan108
 shutdown

** 这是“没有关机”的界面输出 ** *

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

CODE EXTRACT,由于简洁原因而被删除。

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"

2 个答案:

答案 0 :(得分:1)

目前你这样做:

print " shut"
print " no shut"

结果是:

shut
no shut

正如所料。如果你希望它在关闭时打印“关闭”而在没有关闭时打开“关闭”,你需要进行测试:

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

答案 1 :(得分:1)

好吧,有些错误。 1)Python数组的索引为0.所以你对print internet[1]的调用是打印数组的第二个元素。鉴于您在描述中声明“我需要打印列表的整个第一项”,该调用应为print internet[0]

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

此外,你需要做一些条件来确定是否打印字符串“shutdown”或“no shutdown”;现在你打印两个。