String Indexing and String Slicing in Python

String Indexing and String Slicing in Python:

We can use the PyCharm code editor for this example. If you do not know about it then follow this link- How to install PyCharm for Python and create a program in it.

(1) Strings are identified as a contiguous set of characters represented in quotation marks. Python allows single quotes, double quotes, and triple quotes. Python treats single quotes and double quotes in the same manner. When we use triple quotes, strings can span several lines without using the escape character.

(2) Each individual character in a string can be accessed using a technique called indexing. Python indexes the characters in a string from left to right and from right end to left. From left to right, the first character of a string has the index 0 and from the right end to left, the first character of the string is -1 as shown below.

string indexing in python

(3) Example of String Indexing:

  • From Left to Right:
string indexing from left to right in python
  • From Right to Left:
string indexing from right to left in python

(4) In addition to extracting individual characters in a string, you can pick out a group of characters by slicing strings. Slicing works a lot like indexing, but you use two offsets separated by a colon (:) character. The first offset is where Python should start slicing from; the second offset is where it should stop slicing. Again, think of the offsets as the spaces between the characters, not as the characters themselves.

(5) Example of String Slicing:

  • From Left to Right:
string slicing from left to right in python

The first line print(x[0:4]) tells Python to slice between offset 0 and 4. You can see from the above table that there are four characters between these offsets, that’s why we get the output GK S. Similarly for the second line print(y[0:4]). The third line print(x[4:7]) tells Python to slice between offsets 4 and 7. You can see from the above table that there are three characters between these offsets, that’s why we get the output CIE. Similarly for the fourth line print(y[4:7]). The fifth line print(x[0::2]) slices from the beginning to the end of the string, but since the step value is 2, it takes every second character. Similarly for the sixth line print(y[0::2])

  • From Right to Left:
string slicing from right to left in python

Tutorial Python
Tutorial MySQL
Natural Language Processing (NLP)
Basic Components of Computer System
Characteristics of Computer
Applications of Computer
Python (programming language)– Wikipedia

Comments (No)

Leave a Reply