Software DD (Implementation: String Handling) Flashcards
What would be the output of this code?
mystring = “The quick brown fox jumps over the lazy dog”
print(mystring[2])
e
What would be the output of this code?
mystring = “The quick brown fox jumps over the lazy dog”
print(mystring[0:3])
The
What would be the output of this code?
original =”I am a string”
print(original[2:4])
am
What would be the output of this code?
original =”I am a string”
print(original[7:len(original)])
string
What would be the output of this code?
original =”I am a string”
print(original[0:4])
I am
What would be the output of this code?
original =”I am a string”
print(original[-4])
r
What would be the output of this code?
original =”I am a string”
print(original[-6:])
string
What would be the output of this code?
original = “This string is my original”
print(original[0:3:2])
Gives us the following output - as Python will print the characters from position 0 to before position 3 but increasing the position by 2 each time. So will print out the characters at position 0 and 2.
Ti
What would be the output of this code?
original = “This string is my original”
print(original[::-1])
lanigiro ym si gnirts sihT
Generic method:
original = “This string is my original”
newstring = “”
for x in range(len(original)-1,-1,-1):
newstring += original[x]
print (newstring)
Convert string into an ASCII Value
use ord()
Example:
character = ord(“a”)
print(character)
Output: 97
Convert ASCII Value to a string
use chr()
Example:
character = chr(65)
print(character)
Output: A
Example problem from RGC Aberdeen website:
So we can use this to generate a random value between 65 and 90 and then grab the corresponding ASCII value to generate a random uppercase character such as below. This could be a useful technique for generating passwords etc.
import random
character = chr(random.randint(65,90))
What does the modulus function do?
The modulus function or operator gives the remainder of a division. In some languages it is accessed by a predefined function but in Python is performed using the % operator
What would be the output of this code?
remainder = 10 % 3
print(“Remainder = “ + str(remainder))
Remainder = 1
What does int() do?
My Summary: Converts a real number to an integer. Unlike round() it doesn’t round the real number, int() simply cuts the mantissa off so int(6.833333333) would equal 6