tutorials, python tutorial

Python tutorial

Python String Slicing

   Strings are immutable(unchangeble) . You can not alter its content once it is created.


The String "Programmer" has 10 characters, from left to right it is indexed from 0 in incremental order. 0th position has letter 'P', 1st position has letter 'r' , last position i.e N-1(9th) has 'r'

	       -10     -1	

Python supporting reverse indexing which starts from -1, index -1 gives last character in the string i.e 'r', -2 gives 'e' ... -10 gives 'P' character

Slicing or Extract a character or substring from a String

    You can use slicing to access multiple items in the string. Slicing consists of a start index, an end index, and a step size. and these numbers are seperated by colon(:). except colon all these are optional.

*** Slicing always returns new String

Indexing beyond string length(forward or backward) throws an exception called IndexError for ex: s[10] or s[-20] throws IndexError: string index out of range

Slicing Syntax


Slicing Examples

    Slicing in Forward direction

		>>>s='Sam is a Python Programmer'
-- Forward Direction ,  Index starts from 0, 
			end_index is 3(excluding), 
			step_size is optional by default set to 1		
		--extract 'Python' from String
		-- Python P  is positioned at 9 has length 6, 
				so start_index=9,end_Index=9+6(15),step_size=1
		>>> s[9:15]
		--Similarly extract 'Programmer'
		>>> s[16:]
		above example end_index is optional, s[16:] from 16th position to end of the String

    Slicing in Reverse direction

Reverse Direction starts with -ve indexes

			last character is located at -1, 
			--'Programmer' is located in start_index -10, end index is optional
			--'Python' is located in start_index -17, end index is -11

			--'Python Programmer' is located in start_index -len(s)+9, end index is optional
			'Python Programmer'

start_index and End_index can be negative or positive or mixed
Note: forward direction index will be positive , and in Reverse direction index will be negative
			-- from position 9 to position -3 
			Sam is a Python Programmer'
			012      9               25
		       -26                    -3-2-1
			'Python Program'

Remove empty spaces from a given string

			>>>s='A f r i c a'
		-- start_index is 0,end_index is length of the string, step_size is 2 
			getting every alternate character