我有这样的代码在python:python:运算符%和[::]如何工作?
name = "Eti & Iosi"
print "%s" % name[::-1]
输出为:
isoI & itE
有人可以解释这是如何发生的?
我有这样的代码在python:python:运算符%和[::]如何工作?
name = "Eti & Iosi"
print "%s" % name[::-1]
输出为:
isoI & itE
有人可以解释这是如何发生的?
运营商%
是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
并使用简单的字符串格式打印它。
非常感谢! – 2015-02-11 17:05:59
你不明白什么?你读过https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange(它涵盖了切片和'%'字符串格式) ? – jonrsharpe 2015-02-10 18:17:41