Python Slice Operation
A substring of a string is called a slice. Python Slice Operation is used to refer to sub-parts of sequences and strings. The subset of a string from the original string by using the [ ] operator is known as the Slicing Operator. It has the following syntax:
str[start: end]
// where start specifies the beginning index of the substring,
end specifies the index of the last character and str is a string.
Example:
str="PYTHON" print("str[1:5]=",str[1:5]) print("str[:6]=",str[:6]) print("str[1:]=",str[1:]) print("str[:]=",str[:]) print("str[1:20]=",str[1:20])
Output:
str[1:5]= YTHO
str[:6]= PYTHON
str[1:]= YTHON
str[:]= PYTHON
str[1:20]= YTHON
Slice Operation with stride:
In the slice operation, you can specify a third argument as the stride, which refers to the number of characters to move forward after the first character is retrieved from the string. The default value of stride is 1. It means that every character between two index numbers is retrieved.
Example:
str="Welcome to Webeduclick" print("str[2:10]= ",str[2:10]) print("str[2:10:1]= ",str[2:10:1]) print("str[2:10:2]= ",str[2:10:2]) print("str[2:10:5]= ",str[2:10:4])
Output:
str[2:10]= lcome to
str[2:10:1]= lcome to
str[2:10:2]= loet
str[2:10:5]= le
ord() and chr() functions:
The ord() function returns the ASCII code of the character and chr() function returns a character represented by an ASCII number.
Example of ord() function:
ch='S' print(ord(ch))
Output:
83
Example of chr() function:
print(chr(82))
Output:
R
in and not in operators:
in and not in operators can be used with strings to determine whether a string is in another string. These operators are also known as Membership Operators.
Example of in operator:
str1="Welcome to Webeduclick!" str2="to" if str2 in str1: print("Found") else: print("Not Found")
Output:
Found
Example of not in operator:
str1="Welcome to Webeduclick!" str2="the" if str2 not in str1: print("Welcome to Webeduclick") else: print("Welcome to the Webeduclick")
Output:
Welcome to Webeduclick