''' Purpose: Remind you about subscript indexing. Introduce slicing ''' # get access to local module pause. import pause # operator [] is the string index operator -- it provides access to # a string subsequence. depending upon its operands it is all called # subscripting and slicing print( '##### [] is the string index operator' ) s = 'obliviator' print( 's =', s ) print( ' 0123456789' ) ### pause to think what has happened pause.enter_when_ready() print( '##### if the [] operand brackets an int, it is subscripting' ) x = s[ 0 ] y = s[ 4 ] z = s[ 9 ] print( 's[ 0 ] = ', x ) print( 's[ 4 ] = ', y ) print( 's[ 9 ] = ', z ) ### pause to think what has happened pause.enter_when_ready() print( '##### if the [] operand brackets a : expession, it is slicing' ) print() s = input( 'Enter your philosphy of life: ' ) print( 'philosophy:', s ) n = len( s ) left = 1 right = n // 2 s1 = s[ left : right ] s2 = s[ : right ] s3 = s[ left : ] s4 = s[ : ] print( 's[', left, ':', right, '] = ', s1 ) print( 's[', ':', right, '] = ', s2 ) print( 's[', left, ':', '] = ', s3 ) print( 's[', ':', '] = ', s4 ) ### pause to think what has happened pause.enter_when_ready() # bonus -- stripping and splitting # strings can produced strip versions of themselves -- a # version without LEADING or TRAILING whitespace. Internal # whitespace is uneffected. The ability comes from a # a string's method split() # ------ print( '##### stripping' ) q = ' Look there is a Blibbering Humdinger ' q.strip() # q is uneffected. strip() produces # a new string print( "q = '" + q + "'" ) ### pause to think what has happened pause.enter_when_ready() # bonus -- stripping and splitting # strings can produced strip versions of themselves -- a # version without LEADING or TRAILING whitespace. Internal # whitespace is uneffected. The ability comes from a # a string's method split() # ------ print( '##### stripping' ) q = ' Look there is a Blibbering Humdinger ' s = q.strip() # q is still uneffected, but s is a # stripped version of s print( "q = '" + q + "'" ) print( "s = '" + s + "'" ) ### pause to think what has happened pause.enter_when_ready() # strings can produce their component words. The ability # come from a string's method split() # ------ print( '##### splitting' ) f = 'bananas $0.69' c = 'SEAS CS 1112' print( 'f = \'' + f + '\'' ) print( 'c = \'' + c + '\'' ) ### pause to think what has happened pause.enter_when_ready() fruit, price = f.split() # splits fruit into list of individual # words, which for this example is a # fruit and its cost school, subject, number = c.split() # splits person into list of indiviudal # words, which for this example is a # name, home planet, and age print( fruit, 'costs', price, 'per pound' ) print( 'School:', school, ' subject:', subject, ' number:', number ) ### pause to think what has happened pause.enter_when_ready() s1 = f.split() # s1 is a 2-element list s2 = c.split() # s2 is a 3-element list print( 's1 = ', s1 ) print( 's2 = ', s2 ) print()