strings, files and arrays Flashcards
mystring = “Hello”
how can i save the length of the string in the variable x
x = len(mystring)
methods
-methods work similarly to functions.
- they are written like this
mystring.upper()
and return a value
mystring = “Hello”
what methods will return
1) “HELLO”
2) “hello”
1) mystring.upper()
2) mystring.lower()
mystring = “Hello”
what method will count the number of times “e” occurs in the string
mystring.count(“e”)
mystring = “Hello”
what method will replace all instances of “e” with “x” in the string. (output “Hxllo”)
mystring.replace(“e”, “x”)
mystring = “Hello”
how can i retreive the first letter of the string
mystring[0]
mystring = “Hello”
write a loop which prints each letter of this string seperately.
for i in range (len(mystring)):
print(mystring[i])
mystring = “Hello”
how can i take a “slice” of this string, leaving only the letters “ell”
mystring[1:3]
mystring = “Hello”
how can i take a “slice” of this string, leaving out the first two letters
mystring[2:]
mystring = “Hello”
how can i take a “slice” of this string, leaving out the last two letters
mystring[:3]
what does slicing look like in psuedocode
mystring, substring(1,4)
how to reference a file name in your program.
save the name as a string constant. eg.
FILENAME = “highscore.txt”
then it can be used as myfile
given
FILENAME = “highscore.txt”
savetext= “200”
write some code to save 200 to the text document.
with open( FILENAME, “a”) as myfile:
myfile.write(savetext)
given
FILENAME = “highscore.txt”
write some code to save the contents of the document to a variable x
with open (FILENAME, “r”) as myfile:
x= myfile.read()
what are the conditions for reading a text file into a variable
- file must be text only
- must be in your python directory