String slices
- A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
>>> s = 'Monty Python'>>> s[0:5]'Monty'>>> s[6:12]'Python'
-The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last.
- If you omit the first index (before the colon), the slice starts at the beginning of the string.
>>> fruit = 'banana'>>> fruit[:3]'ban'
- If you omit the second index, the slice goes to the end of the string:
>>> fruit[3:]'ana'
- If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:
>>> fruit = 'banana'>>> fruit[3:3]''
- By default, Python sets this increment to 1, but that extra colon at the end of the numbers allows us to specify the slicing increment.
>>>s=”karpagam”>>>s[::2]kraa
- It also possible to apply negative index.
>>>s=”karpagam”>>>s[-3:-1]ga
References
- Allen B. Downey, “Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
- Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd., 2011.
- John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013
- Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
- Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015. 4. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
- Charles Dierbach, ―Introduction to Computer Science using Python: A Computational Problem-Solving Focus, Wiley India Edition, 2013.
- Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013.