2016-11-09 116 views
-1

我是新來的編程人員,並試圖弄清楚在不同字母的打印語句中%符號的作用。我理解幾乎所有這些接受%u所做的事情。它似乎只是打印538作爲一個整數。我看到前面的打印語句用'u'打印在unicode中,但我不知道它是否適用於%u。python符號%u和%o

print "In honor of the election I present %d" % 538.0 # integer 
print "In honor of the election I present %o" % 538.0 # octal 
print "In honor of the election I present %u" % 538.0 # ? 
print "In honor of the election I present %x" % 538.0 # lowercase hexadecimal 
print "In honor of the election I present %X" % 538.0 # uppercase hexadecimal 
print "In honor of the election I present %e" % 538.0 # exponential 
print "In honor of the election I present %i" % 538.0 # integer 

輸出如下:

In honor of the election I present 538 
In honor of the election I present 1032 *emphasized text* 
In honor of the election I present 538 *emphasized text* 
In honor of the election I present 21a 
In honor of the election I present 21A 
In honor of the election I present 5.380000e+02 
In honor of the election I present 538 

我也有與%o有點麻煩,這個號碼。我剛剛瞭解到八進制打印是什麼,我想它會輸出132538 --> 8^3 = 512 *(1) + 26, 8^1 = 8*(3) + 2, 8^0 = 1*(2)),但輸出是1032。 0從哪裏來?

+1

0是因爲在那個數字中有0次8^2 = 64。八進制132將是2 * 8^0 + 3 * 8^1 + 1 * 8^2。 – melpomene

回答

4

the docs從,%u

作廢類型 - 它是相同的'd'

%o告訴print解釋538作爲基10,並將其轉換爲八進制數。 538基座10(538 )是1032以八進制(1032 ):

1 * 8^3 + 0 * 8^2 + 3 * 8^1 + 2 * 8^0 
= 512 + 0 + 24 + 2 
= 538 

它顯示1032,因爲這些都是8 Ñ適當的係數。 0對應於8 。如果你離開它,你就會有132 = 1 * 64 + 3 * 8 + 2 = 90 ,而不是538

所以,沒有什麼奇怪的存在。