In this example program, we have defined a variable named str and assigned a string value “Good Morning” to it. # This statement starts to slice the string at index 5 and slices up to end position (including). # This statement produces an empty string. # This statement does not slice the string and displays the entire string. # This statement starts string slicing at index 5 and slices up to end. # This statement starts to slice string from the beginning and slices up to index 6 and returns the result. Print('Substring from 0 to 4:',substring1) # This statement starts to slice string at index 0 and slices up to index 4 and returns the result. Hence, 0:4 means 0 to 3 sequence of characters, not 4th character. Thus, the first index number is inclusive and the last index number is exclusive. The first index number in the slicing operation represents the position from where the slice starts and the second index number after the colon indicates where slice will end. The square brackets () is a subscript operator. We have obtained a substring of four characters starting from 0 to 4. The sequence of characters of this string will be index, starting from 0, and so on, as shown in the below figure. In the above code, we have created a variable named str and assign it with a string value “Technology”. My_substring = str # extracting substring by specifying a range of index numbers. # Program to demonstrate the extracting of substring from main string in Python. Let’s write a simple program to extract a substring within a string by specifying a range of index numbers separated by a colon. The start and stop values should be an integer. This slice syntax returns a substring beginning at the start index and extending up to but not including the stop index. It also separates the two indices in the square brackets ().
0 Comments
Leave a Reply. |