Give at least three examples that show different features of string slices. Describe the feature illustrated by each example. Invent your own examples. Do not copy them for the textbook or any other source.

print('Example 1: Substrings and every i-th character')

string = 'Describe the feature illustrated by each example.'

strA = string[0:9]

strB = string[9::2]

strC = string[10::2]

listD = [x + y for x, y in zip(strB, strC)]

string2 = strA + ''.join(listD)

print(string2)

assert string2 == string

print('')




print('Example 2: Ranges and slices and slice objects')

# docs.python.org/3/library/functions.html#slice

nums = list(range(1,10))

nums2 = nums[:-1:2] + [nums[-1]] + nums[1::2] + nums[50:100:3]

nums3 = list(range(1,10,2)) + list(range(2,10,2))

print(nums2)

print(nums3)

assert nums2 == nums3

string = 'Describe the feature illustrated by each example.'

string2 = string[:-1:2] + string[-1] + string[1::2] + string[50:100:3]

lstA = [string[i] for i in range(0,len(string),2)]

# lstB = [string[i] for i in range(1,len(string),2)]  # what a mess

# lstB = string[slice(1,len(string),2)]  # string, not a list :)

lstB = list(string)[slice(1,len(string),2)]

lstC = [string[i] for i in range(50,100,3) if i in range(len(string))]

string3 = ''.join(lstA) + ''.join(lstB) + ''.join(lstC)

print(string2)

print(string3)

assert string2 == string3

print('')




print('Example 3: Copying and reversing')

string = 'Describe the feature illustrated by each example.'

string2 = string[:]

try: string2[-1] = '!'

except TypeError as e: print(e)

string3 = string

try: string3[-1] = '!'

except TypeError as e: print(e)

string = ''.join(reversed(string))  # it's slower then slicing

string2 = string2[::-1]

print(string)

print(string2)

print(string3)

assert string2 == string

print('')

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source