2013-07-25 28 views
3

我是Python的新手,並試圖學習如何使用for語句以某種方式顯示信息....是否有方法使用for語句來顯示這樣的列表?Python:For語句顯示特定字符​​串的列表?

w = "Fa1/1       connected 42   a-full a-100 10/100BaseTX" 
v = w.split() 

x=v[0] 
print "Port ", x 

y=v[1] 
print "Status ", y 

z=v[2] 
print "VLAN ", z 

a=v[3] 
print "Duplex ", a 

b=v[4] 
print "Speed ", b 

c=v[5] 
print "Type ", c 

------------------------- 
Port Fa1/1 
Status connected 
VLAN 42 
Duplex a-full 
Speed a-100 
Type 10/100BaseTX 

我已經嘗試了很多不同的方法,但要獲得價值和指數誤差....

感謝您的幫助....

回答

5

像這樣的事情?

>>> w = "Fa1/1       connected 42   a-full a-100 10/100BaseTX" 
>>> firstList = ['Port', 'Status', 'VLAN', 'Duplex', 'Speed', 'Type'] 
>>> testList = zip(firstList, w.split()) 
>>> for a, b in testList: 
     print a, b 


Port Fa1/1 
Status connected 
VLAN 42 
Duplex a-full 
Speed a-100 
Type 10/100BaseTX 
+0

上帝它是如此簡單,現在我看到它...我覺得自己像一個白癡... 謝謝 –

2

你的意思是,像這樣?

w = 'Fa1/1     connected 42   a-full a-100 10/100BaseTX' 
f = 'Port {0}\nStatus {1}\nVLAN {2}\nDuplex {3}\nSpeed {4}\nType {5}\n' 
s = f.format(*w.split()) 

print s 

Port Fa1/1 
Status connected 
VLAN 42 
Duplex a-full 
Speed a-100 
Type 10/100BaseTX 

在這種情況下使用format string比在由split()返回的結果明確地迭代簡單。

+0

謝謝,這也可以 –

+1

@JustinParker它更短,更靈活;) –

相關問題