[Tutor] Counting a string backwards

Peter Otten __peter__ at web.de
Mon May 29 01:54:10 EDT 2017

Steven D'Aprano wrote:

> Because 0 always means the start of the string, how do you slice to the
> end? You can use the length of the string (in this case, 7) or you can
> leave the ending position blank, and it defaults to the length of the
> string:

For completeness, there's a third option, None, which is equivalent to a 
missing value:

>>> "Machine!"[None:None]

Sometimes this is even moderately useful:

>>> def clip(s, n):
...     return s[:-n or None]
>>> for i in reversed(range(5)):
...     print(i, clip("Machine!", i))
4 Mach
3 Machi
2 Machin
1 Machine
0 Machine!

More information about the Tutor mailing list