sampleqa.in tutorials, python tutorial

Python tutorial


Python String Slicing



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

		>>>s='Programmer'
		>>>print(s)
		Programmer
	

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'

		0123456789
		Programmer
	       -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

	
		str[start_index:end_index:step_size]
	

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		
		
		>>>s[0:3]     
		'Sam'
		
		--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]
		'Python'
		
		--Similarly extract 'Programmer'
		>>> s[16:]
		'Programmer'
		
		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, 
			
			>>>s[-1]
			'r'
			
			--'Programmer' is located in start_index -10, end index is optional
			
			>>>s[-10:]
			'Programmer'
			
			--'Python' is located in start_index -17, end index is -11
			
			>>>s[-17:-11]
			'Python'

			--'Python Programmer' is located in start_index -len(s)+9, end index is optional
			>>>s[-(len(s))+9:]
			'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
			>>>s[9:-3]
			'Python Program'
			
			>>>s[9:-11]
			'Python'
		

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 
				OR
			getting every alternate character
		
		
			>>>s[::2]
			'Africa'
		

ADS