Sunday, 15 September 2019

Sub-string in Python using Slicing

Python - Sub-string Function using Slicing

Index number of a string can be used to obtain individual characters from a string. Slicing can be used to obtain a sub-string from the given string. Check the following examples:

>>> str = 'PythonPracticals'

#Code to refer position 0 (included) to 3 (excluded)
>>> str[0:3]
'Pyt'

# position 0 (included) to 6 (excluded)
>>> str[0:6]
'Python'

# position 4 (included) to 6 (excluded)
>>> str[4:6]
'on'

In slicing, the starting index number is included and ending index number is excluded in the result. 

If we omits the first index number in slicing, it will be considered as 0. An omitted second index will be considered as the size of the string being sliced. Observe following interesting string slicing examples:

>>> str = 'PythonPracticals'

# prints from beginning to index 6(excluded)
>>> str[:6]
'Python'

# prints from beginning to index 16(excluded)
>>> str[:16]
'PythonPracticals'

# prints from index -4 to end of string
>>> str[-4:]
'cals'

>>> str[:6] + str[6:]
'PythonPracticals'

>>> str[6:] + str[:6]
'PracticalsPython'

For non-negative indices, the length of a slice(substring) is the difference of the indices. If both are within proper boundary (limits), the length of str[1:4] is 3.

Attempting to use out of range index (too large/small) will result in an error as shown below:

>>> str = 'PythonPracticals'
>>> str[101]  # the str has only 16 characters
Traceback (most recent call last):
  File "< pyshell#1>", line 1, in <module>
IndexError: string index out of range

Out of range slice indexes are handled properly by Python interpreter. Check following example:

>>> str = 'PythonPracticals'
>>> str[6:30]
'Practicals'

Python strings cannot be changed — they are immutable. Therefore, assigning value to a specific index position will result in an error.

>>> str[0] = 'K'
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
       str[0]=’K’
TypeError: 'str' object does not support item assignment

If you want to modify your string, you should create a new one:

>>> 'K' + str[1:]
'KythonPracticals'

String Length using in-built function len()

Built-in function len() returns the length of a given string:
>>> str = 'PythonPracticals'
>>> len(str)
16

>>> str1 = 'K. Patel'
>>> len(str1)
8

>>> print(len(str+str1))
24

* * * * *


No comments:

Post a Comment