2015-02-10 95 views
-3

我有這樣的代碼在python:python:運算符%和[::]如何工作?

name = "Eti & Iosi" 
print "%s" % name[::-1] 

輸出爲:

isoI & itE 

有人可以解釋這是如何發生的?

+3

你不明白什麼?你讀過https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange(它涵蓋了切片和'%'字符串格式) ? – jonrsharpe 2015-02-10 18:17:41

回答

2

運營商%old-style string formatting operator。字符串格式替換所有%s(還有其他類型)與您在操作員的正確成員中給出的元組內容(在這種情況下,因爲只有一個%s,您可以只提供一個字符串)。例如:

>>> s = 'Hello %s!' 
>>> print s % 'world' 
'Hello world' 

>>> s = 'I like %s and %s.' 
>>> print s % ('red', 'blue') 
'I like red and blue.' 

[start:end:step]操作者列表(或支持任何索引對象)slicing operator[::-1]意味着take the object items from start 0 to end -1 (i.e. all of them) every -1 step,這會導致您的字符串被顛倒。

您的代碼反轉name並使用簡單的字符串格式打印它。

+0

非常感謝! – 2015-02-11 17:05:59