Answer to Question #167684 in Python for Praise

Question #167684


Learning Journal Unit 5

1. Consider the loop from Section 8.3 of your textbook.


prefixes = 'JKLMNOPQ'

suffix = 'ack'

for letter in prefixes:

   print(letter + suffix)

Put this code into a Python script and run it. Notice that it prints the names "Oack" and "Qack".

Modify the program so that it prints "Ouack" and "Quack" but leaves the other names the same.

Include the modified Python code and the output in your submission.

2. 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.



1
Expert's answer
2021-03-01T02:04:29-0500
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
    if letter not in 'OQ':
        print(letter + suffix)
    else:
        print(letter + 'u' + suffix)

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')

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 = 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('')

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

xty
18.09.21, 16:57

Thank you

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS