2014-01-27 196 views
-3

我使用了一本書所以這段代碼是從書 我需要它,從蟒蛇2.5〜3.3我如何轉換這個Python代碼?

my_name = 'Zed A. Shaw' 

my_age = 35 

my_height = 75 

my_weight = 180 

my_eyes = 'Blue' 

my_teeth = 'White' 

my_hair = 'Brown' 



print "Let ' s talk about %s." % my_name 

print "He ' s %d inches tall." % my_height 

print "He ' s %d pounds heavy." % my_weight 

print "He 's got %s eyes and %s hair." % (my_eyes, my_hair) 

print "His teeth are usually %s depending on the coffe." % my_teeth 
+2

這個問題似乎是脫離主題,因爲它是關於基本的Python語法。 – iCodez

回答

1

您需要使用print作爲一個內置功能:

print("Let ' s talk about %s." % my_name) # Note the parenthesis 

另外,如果你是移動到Python 3.x的,你應該養成使用str.format代替%的習慣:

print("Let ' s talk about {}.".format(my_name)) 

雖然%仍然有效,str.format是現代/首選的字符串格式化方式。


總而言之,你的代碼應該是這樣的:

my_name = 'Zed A. Shaw' 

my_age = 35 

my_height = 75 

my_weight = 180 

my_eyes = 'Blue' 

my_teeth = 'White' 

my_hair = 'Brown' 



print("Let ' s talk about {}.".format(my_name)) 

print("He ' s {} inches tall.".format(my_height)) 

print("He ' s {} pounds heavy.".format(my_weight)) 

print("He 's got {} eyes and {} hair.".format(my_eyes, my_hair)) 

print("His teeth are usually {} depending on the coffee.".format(my_teeth)) 
+0

這應該在2.x和3.x上運行,順便說一句。 – dstromberg

0

打開print "foo"print("foo")

1

2to3可以處理基本語法轉換,如這一點,並會產生正確的結果你的腳本的情況。我強烈建議你使用它。

假設你的文件名是「foo.py」,那麼你就可以運行這個命令來產生正確的Python 3語法:

2to3 -w foo.py 

值得一提的是,格式化是遺留在Python 3,但它仍然有效;我建議您儘早將它轉換爲more widely accepted form