In: Computer Science
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 .
1 SOL)
Given Python code implementation:
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print(letter + suffix)
Code Picture:
Given code's output:
NOTE: Above picture is the output for the given code in the question.
Modified python code in our required format:
prefixes = "JKLMNOPQ" #Prefixes string
suffix = "ack" #Suffix string
for letter in prefixes: #Traversing the given prefixes string
if letter == "O" or letter == "Q": #If the prefix is either "O" or or "Q"
print(letter + "u" + suffix) #Printing the word by adding letter "u" to the word after "O" or "Q" letter
continue #Program execution won't go down in this "for" loop
print(letter + suffix) #Printing the remaining words as it is.
CODE implementation:
Required output:
NOTE: Here, from above you can see that for the prefix "O" and prefix "Q" the output has been changed compared from the first uploaded output.
NOTE: Be aware of the indentation while copying the code into your editor by observing the above uploaded CODE pictures
2 SOL)
a) Reversing the string:
We can reverse a string by the following:
Output:
b) Slicing the string with negative indices:
We can slice the string with negative indices :
eg: string[-10:-1] ---> means accessing the last 10 characters of a string.
Implementation:
Output:
NOTE: Here as you can see from the string "United States of America" only the last 9 characters are only printed..(Space is also a character)
c) Skipping the characters while traversing :
We can skip the characters while traversing the string by the following:
eg: string[0:11:2] ---> accessing only every second character of the string starting from index 0 to index 11...Let's implement this by an example for a better understanding.
Implementation:
Output:
NOTE: From the string "United States of America" only every two characters are printed..
United_States of America ---> Only the underlined characters are only printed from (index 0 to index 18 skipping every 2 characters)
d) printing every nth character from last :
We can print every third character from last by the following :
eg: string[-1:-16:-3] ---> means printing every 3 character from the last of a string..
Implementation:
Output:
NOTE: syntax will be string[starting: end: step] ---> step : skipping the every stepth index