Weekly Topics
•
In this weeks lecture and lab we will look at the following areas:
•
Slicing up strings into substrings using ranges,
•
Finding specific substrings within strings,
•
General file handling in Python, including reading and writing to text files,
•
Casting between data types (including safe and unsafe conversions),
3
String Recap
•
We’ve seen that we can work with string (str) data in a number of different ways. We can just assign it, like this:
name = “Bob”
print(name)
•
Or we can combine it and use it in substitutions, like this:
firstName= “Boris”
lastName= “Becker”
print(firstName, lastName)
•
Or we can ask the user for some string data, and then use it like this:
name = input(“Please enter your name: “)
print( “Hi there, 0!”.format(name) )
4
Strings and Operators Recap
•
We also saw that although we couldn’t use the plusoperator between a number and a non-number (such as a string), we could add together strings quite happily, like this:
first = “Python”
second = ” is ” # Notice there are spaces either side
third = “great!”
full = first + second + third
print(full)
•
Which gives us:
Python is great!
Note: Without the additional spaces somewhere we’d end up with Pythonisgreat. Whichisn’treallyallthatgreatisit?
5
Multiplying Strings
•
We’ve briefly mentioned that we can multiplystrings -so for example in Python, we can multiplya string value by a number to obtain multiples of the string, like this:
answer = “No”
print(“Would you like some brusselssprouts?”)
print( (answer * 5) + “!” )
•
The last part of this gives us:
NoNoNoNoNo!
6
Multiplying Strings (Cont’d)
•
By multiplying strings we can also do things like this:
print(“All work and no play makes Jack a dull boy.n” * 99)
•
Or maybe:
print(“Excited: ” + (“!” * 1) )# !
print(“Really excited: ” + (“!” * 3) )# !!!
print(“Really, really excited: ” + (“!” * 6) )# !!!!!!
Newline character
7
Substrings
•
When working with strings, we can extract partof a string (which is called a substring), like this:
letters = “ABCD”
print(letters[0]) # A
print(letters[1]) # B
print(letters[2]) # C
print(letters[0:2]) # AB
print(letters[1:-1]) # BC (-1 is the last element)
•
When we use this [start:end]notation, what we’re really saying is:
•
Start and includethe first character we specify as the start of our range,
•
But excludethe last character that we specified as the end of our range.
•
Just like the range statement: range(0, 3)gives use the set of data [0,1,2], when extracting strings using [start:end], we includethe start of the range, but excludethe last element of the range.
You could also do this one as:
letters[1:3]
8
Substrings (Cont’d)
•
To print a string, we know we can use Python code like this.
phrase = “Knowledge is power.”
print(phrase)
•
But what if we only wanted to print out the first 9 characters? In this case, we can print out the word Knowledge(which is 9 characters) by specifying a range that goes from character 0to character 9 like this:
phrase = “Knowledge is power.”
print(phrase[0:9]) # Knowledge
•
Why do we get 9 characters when we specified the range 0 to 9 (which is 10 characters?) Because K is the 0thcharacter, and we get the range:
[start-location-inclusive: end-location-exclusive]
9
Substrings (Cont’d)
•
So in our example we said:
Start at character 0, keep going until, but do# not include, character 9
print( phrase[0:9] )
•
But if we omit(which just means do not include) a value either side of the colon in [start : end] then Python takes that as:
•
[:9] means “Go from the startup to but not includingthe 10thcharacter”,
and
•
[9:]means “Go from the 10thcharacter to the end of the string”.
•
Let’s take a look at it in action…
10
Substrings (Cont’d)
•
If we wanted to print from the beginning of the string to the 10thactual character, then we could use code like this:
phrase = “Knowledge is power.”
print(phrase[:9]) # Knowledge
•
And to print from the character at index 11 to the end of the string (however long that is!), we can use code like this:
phrase = “Knowledge is power.”
print( phrase[10:] ) # is power.
•
What code would we have to use to print out just the “is”part of the string?
11
Finding Substrings
•
If we want to find a substring within a string in Python, we can use the findfunction, which works like this:
quote = “Eat when hungry, sleep when tired.”
first = quote.find(“when”)
print( “‘when’ starts at location: 0”.format(first) )
•
Which will display:
‘when’ starts at location: 4
•
The findfunction will return one of two integer values:
•
If the substring existsin the string it will return the character number of the first occurrence of the substring, or
•
If the substring does not exist in the string, it will return the value -1.
Because the first character is at index 0, not at index 1!
12
Finding Substrings (Cont’d)
•
To use a negative example, if we search for a substring which does not exist anywhere in our string, we might do so like this:
quote = “Eat when hungry, sleep when tired.”
first = quote.find(“grumpy”)
print( “‘grumpy’ starts at location: 0”.format(first) )
•
Which will display:
‘grumpy’ starts at location: -1
13
Finding Substrings (Cont’d)
•
By using this known value of -1 for a negative match, we can check if a substring exists in a string and then do one thing if it does, or another thing if it doesn’t, for example:
ingredients = “Flour, Milk, Eggs, Sugar, Apricots”
if (ingredients.find(“Chainsaws”) == -1):
print(“There are no chainsaws in this recipe!”)
else:
print(“Woohoo! Chainsaws are delicious!”)
•
Another example could be:
email = “aravind.adiga@federation.edu.au”
if (email.find(“@”) == -1):
print(“I doubt this is a valid email address.”)
else:
print(“This might be a valid email address.”)
14
Finding Substrings (Cont’d)
•
The findfunction, like Python in general, is case-sensitive.
•
This means that the string we search for must EXACTLY match the exact uppercase and lowercase specific spelling of our search string.
•
For example, the following code will notfind a substring match:
msg= “APATHY ERROR: Don’t bother striking any key.”
location = msg.find(“error”)
print(location) # Prints -1
•
Instead, if we wanted to find the word “ERROR”, we’d have to specify it in the same case that it appears, like this:
location = msg.find(“ERROR”)
print(location)# Prints 7
Question: How might we make find work in a non-case sensitive way?
15
Finding Substrings (Cont’d)
•
When we find substrings, we’re not really looking for distinct words-we’re just looking for an exact match anywherein the string.
•
So for example, if we try out the following code:
quote = “No good deed will go unrewarded.”
location = quote.find(“go”)
print(location)
•
We won’t find the word “go” which comes before “unrewarded” right away -instead, we’ll find the “go” in the first half of “good”!
•
So the result stored in our locationvariable will be 3and not 18.
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
22
23
24
25
26
27
28
29
30
N
o
g
o
o
d
d
e
e
d
w
i
l
l
g
o
u
n
r
e
w
a
r
d
e
d
.
16
Finding Substrings (Cont’d)
•
We’ve only been using a single parameter with the find function, which has been the substring we want to find…
•
…but, we can also provide findwith a second parameter -which is the location in our source string where the function should start looking.
•
For example:
quote = “No good deed will go unpunished.”
location = quote.find(“go”, 4)
print(location)
•
This will start at character index 4 (the 5thcharacter) and look for the substring “go” -which turns up at location 18.
•
What you think would happen if we’d specified to start searching at character number 3in our second find statement?
17
Finding Substrings (Cont’d)
•
In the previous example, if we wanted to find all the occurrences of a substring within a string, then we had to manually specify where to start searching -but this is rather ‘manual’, so let’s automate it using a do-whileloop:
quote = “No good deed will go unrewarded.”
location = 0
while True:
location = quote.find(“go”, location)
if (location != -1):
print( “Found substring at: 0”.format(location) )
location += 1
else:
break
•
This will print out:
Found substring at: 3
Found substring at: 18
Quiz: Why is a “do-while” (equivalent) loop the best kind of loop for this specific task?
18
Finding Substrings (Cont’d)
•
Rather than just looking for a specific substring which we specify in the code,we could also find all occurrences of a user-providedsubstring, like this:
quote = “The large print giveth & the small print taketh away.”
match = input(“Please enter the substring to find: “)
location = 0
while True:
location = quote.find(match, location)
if (location != -1):
print( “Found substring at: 0”.format(location) )
location += 1
else:
break
19
Finding Substrings (Cont’d)
•
We might also like to counthow many occurrences we find, like this:
quote = “The large print giveth & the small print taketh away.”
match = input(“Please enter the substring to find: “)
count = 0
location = 0
while True:
location = quote.find(match, location)
if (location != -1):
print( “Found substring at: “.format(location) )
location += 1
count += 1
else:
break
print(“Found 0 occurrences of ‘1’”.format(count, match) )
20
Converting Strings to Lists of Characters
•
Python allows us to easily convert a string into a list of characters via the built-in list() function, for example:
quote = “A thing of beauty is a joy forever.”
quote_list= list(quote)
print(quote_list)
•
This will print out, as you might imagine:
[‘A’, ‘ ‘, ‘t’, ‘h’, ‘i’, ‘n’, ‘g’, ‘ ‘, ‘o’, ‘f’, ‘ ‘, ‘b’, ‘e’, ‘a’, ‘u’, ‘t’, ‘y’, ‘ ‘, ‘i’, ‘s’, ‘ ‘, ‘a’, ‘ ‘, ‘j’, ‘o’, ‘y’, ‘ ‘, ‘f’, ‘o’, ‘r’, ‘e’, ‘v’, ‘e’, ‘r’, ‘.’]
•
We can jointhe string back together like this:
quote2 = “” # What to put between each element
quote2 = quote2.join(quote_list) # quote2 is now as per orig
Try this: s = “-“; seq= [‘a’, ‘b’, ‘c’]; print(s.join(seq)) # Prints a-b-c
21
Determining If A String Is Purely Alphabetical or Numerical
•
Sometimes we may want to check if something is a number or a letter -and again, Python comes to the rescue with the isalpha() and isdigit() functions.
•
Let’s give it a shot:
s = “123456”
print( s.isdigit() ) # True -only digits in string
s = “12Three456”
print( s.isdigit() ) # False -not purely digits
s = “ElvisPresley”
print( s.isalpha() ) # True -all chars alphabetical
s = “Elvis Presley”
print( s.isalpha() ) # False -space ‘ ‘ is not a letter!
22
Stripping Whitespace
•
Whitespaceis the spaces (i.e. ‘ ‘) and tabs in your text data. We like whitespace, becausewithoutitallourwordsruntogetherandaredifficulttoread.
•
However, sometimes we end up with whitespace at the beginning or end of our strings that we want to get rid of, and to do this we can use Python’s strip(), lstrip(), and rstrip()functions.
•
lstrip() and rstrip() strip the whitespace from the left and right sides respectively, while the strip()function strips all whitespace from both sides:
padded_string= ” t It’s me, Mario! “
print(padded_string.lstrip()) # “It’s me, Mario! “
print(padded_string.rstrip()) # ” t It’s me, Mario!”
print(padded_string.strip()) # “It’s me, Mario!”
23
Working with Files in Python
•
Like any good language, Python allows us to work with files, but also like any good language, we need to know what we want to dowith the files before we open them. The options we have available are:
1.
To open a file for reading only -which is mode r,
2.
To open or create a file for writing only -which is mode w,
3.
To open a file for appending only -which is mode a, and
4.
To open a file for reading andwriting, which is mode r+.
•
The difference between options 2and 3above is that if a file exists and has some data in it already:
•
If we open it for writing, any existing file contents will be discarded, and
•
If we open it for appending, any new data we write can be added to the end of the existing data in the file.
24
Opening a File in Python
•
Before we can read from a file, we have to open the file, like this:
file = open(“Names.txt”, “r”)
or
file = open(“Names.txt”, “w”)
or
file = open(“Names.txt”, “a”)
or
file = open(“Names.txt”, “r+”)
Open Names.txt for reading.
Open Names.txt for writing.
Open Names.txt for appending.
Open Names.txt for reading AND writing.
25
Reading Lines from a File
•
We can open a file for reading, read a line from the file and print it like this:
file = open(“Quotes.txt”, “r”)
first = file.readline()
print(first)
•
Once we’ve read the first line of a file, each subsequent call to readlinewill read the next line of the file, so to get the second and third lines of the file we could write:
second = file.readline()
print(second)
third = file.readline()
print(third)
file.close()
The Quotes.txt file must be in the same directory as your Python script for this to work!
The close function is explained in detail on the next slide!
26
Reading Lines from a File (Cont’d)
•
When we’ve finished working with a file, we should alwaysclose the file for two important reasons:
1.
When we close a file, we free up any resources like RAM and buffers that Python allocated itself in order to work with the file, and
2.
If we’ve opened a file and modified it, the changes only get written to the file when the file is closed! So if we create a new file or modify an existing file and forget to close it -the changes won’t “stick”!
•
Another important thing happens when we close a file, and that’s that the file pointer(which is just a piece of memory which stores where we are in the file gets reset back to zero).
•
This might sound complicated, but it’s really very simple, as we’ll see on the next slide!
27
Reading Lines from a File (Cont’d)
•
As we saw, if we open a file and then read a line from the file, the next time we read a line from the file we’ll get the second line of the file:
file = open(“Quotes.txt”, “r”)
first = file.readline()
second = file.readline()
•
But if I closethe file and then re-open it, and then read from the file again -I won’t be reading the thirdline -I’ll be reading the firstline again!
file.close()
file.open(“Quotes.txt”, “r”)
third = file.readline()
print(third)
file.close()
Reads the first and second lines -no problem!
Our thirdvariable will nothold the third line of the file -it’ll hold the firstline of the file because we closedthe file, which reset the file pointer!
28
Reading An Entire File Line-by-Line (one method)
•
Now that we know a little about loops, and a little about files, we can write a small script to read every line of a file and display it on the screen, like this:
file = open(“Names.txt”, “r”)
while True:
line = file.readline()
if (line != “”):
print(line)
else:
break
Don’t forget to close the file when we’re done with it!
file.close()
•
This will work… but we can do better.
If we read a line from a file, and the line we receive is “”(i.e. nothing -a blank line) then we’ll assume we’ve reached the end of the file!
29
Reading An Entire File Line-by-Line (a better method)
•
Instead of writing a “do-while” equivalent, Python can do a lot of the heavy lifting for us if we just use a forloop, likethis:
file = open(“Names.txt”, “r”)
for line in file:
print(line)
Don’t forget to close the file when we’re done with it!
file.close()
•
Ha! How easy was that?! In the above code, Python treats our fileas a listof strings, where each line is an individual element of the list. This is much like we saw previously that we could store the names of the band members in the Beatles by using:
beatles= [“John”, “Paul”, “George”, “Ringo”]
Notice that we don’t even have to call readline()when we use this method!
30
Reading An Entire File Into A List
•
Python goes even further than single line reading with readline-it allows us to read ALLthe lines in a file (however many there may be) using a single command, which is:
readlines()
•
Now, we can read an entire file into a list like this:
file = open(“Quotes.txt”, “r”)
lines = file.readlines()
print(lines[0])
print(lines[1])
file.close()
Quiz: What character do you think “delimits” each line? (i.e. marks the end of each line)
Notice the s on the end of lines!
Display the secondline of the file
Display the firstline of the file
Read the entire file and place each line into the lines list
31
Counting Elements in a List
•
When we have a list of data in Python, we can find out how many elements are in the list by using the lenfunction (short for length), for example:
beatles= [“John”, “Paul”, “George”, “Ringo”]
size = len(beatles)
print(size) # Prints 4. Elements are at indices 0, 1, 2 & 3
•
Although wecan loop through all the elements in a set using…
for loop in beatles:
print(loop)
•
…sometimes it’s good to know how many elements we’re working with, so after running the code at the top of the slide, another way to print each element in turn could be by using code like the below:
for loop in range(0, len(beatles)):
print(beatles[loop])
Note: If we’d already calculated the size variable as size = len(beatles)then we could use range(0, size)
32
Counting Elements in a List (Cont’d)
•
When we apply this to files, we might use code like this:
file = open(“DownAndOut.txt”, “r”)
lines = file.readlines()
lineCount= len(lines)
print( “Line count is: 0”.format(lineCount) )
file.close()
•
If we wanted to, we could then display the file by looping through all the elements of our list and printing each out in turn like this:
for loop in range(0, lineCount):
print(lines[loop])
•
Or alternatives, we could do:
for line in lines:
print(line)
Same result!
33
Reading a User-Selected File
•
We could also ask the user which file they’d like to open, and then go and do it:
Ask user for filename
filename = input(“Please enter a filename: “)
Open the file the user specified for reading
file = open(filename, “r”)
Read the entire contents of the file into a set
line = file.readlines()
Count how many elements are in the set
lineCount= len(line)
Display the line count
print( “There are 0 lines in 1”.format(lineCount, filename) )
Close the file when we’re done with it
file.close()
34
Writing To Files
•
Now we’ve seen how to read from files, let’s start writing our own files.
•
In the example below, we’ll just write the numbers 1 through to 20 into a new file called Numbers.txt:
file = open(“Numbers.txt”, “w”) # “w” for writing!
set = range(1, 21)
for value in set:
strValue= str(value)
file.write(strValue+ “n”)
file.close()
•
Adding the n (newline) means that each number in the file is on its own line rather than all running together to form 1234567891011121314151617181920!
We’re casting our integer values to strings before writing them! This is explained on the next slide!
35
Writing to Files (Cont’d)
•
There is one important thing to know about writing to files in Python, which is:
We can only, everwrite string data to files!
•
This means that if we had an integer value, or a floating point value, or a booleanor any other type of value -before we can write it to a file, we have to first convertit into a string.
•
Luckily for us, this is very easy -as we’ll see on the next slide…
36
Casting Data To Strings
•
We can convert any type of data to a string by using what’s called a cast:
number = 5
print( type(number) ) # type i.e. 5
strNumber= str(number)
print( type(strNumber) ) # type i.e. “5”
pi = 3.14159
print( type(pi) ) # type i.e. 3.14159
strPi= str(pi)
print( type(strPi) )# type i.e. “3.14159”
raining = False
print( type(raining) ) # type i.e. False
strRaining= str(raining)
print( type(strRaining) ) # type i.e. “False”
RED= Cannot be written to file.GREEN= Can be written to file.
CASTOPERATION
S
37
Casting Between Types
•
As we’ve seen, if we want to change the underlying type of data, then we can do so using casts:
intNum= 5
castNum= float(intNum)
print(castNum)# 5.0
•
However, sometimes this may result in us losing precision, as shown below:
floatNum= 1.234;
castNum= int(floatNum)
print(castNum) # 1
•
When we cast data to a string, we never lose any precision -but we can no longer do any useful maths with a string, unless we first cast it back to some kind of number again!
intvalue 5cast to float value 5.0.
This is safe-no loss of precision.
float value 1.234 cast to the intvalue 1
This is unsafe-precision is lost!
38
Casting Back And Forth
•
Python will use mathematical operators on our data in a way which fits with that particular kind of data. For example:
number = 6
print(number * 3) # Prints out: 18
strNumber= str(number)
print(strNumber* 3) # Prints out: “666”
castBack= int(strNumber)
Prints out 18 again, because we converted (or ‘cast’)
our string data back into an integer!
print(castBack* 3)
39
Casting Errors
•
We did mention this previously, but just for a tiny recap -sometimes we may try to cast data between two different types and it’ll fail.
•
This is because some things simply cannot be represented as a number, for example:
myString= “one hundred and twenty three”
myInt= int(myString) # CAST FAIL!
•
For casts to work successfully, they must be given data in the correct format, so the following cast will work fine without any issues:
myString= “123”
myInt= int(myString) # OK! 123
Harry Potter is a wizard. You are not. Stick to data casting =P
40
Appending Files
•
Each time we open a file in writing mode (“w”) -we erase the file’s contents and effectively create a new file with the same name.
•
If we want to add data to the end of a file (i.e. append it), then we need to open the file in append mode, like this:
file = open(“Numbers.txt”, “a”)
set = range(21, 41)
for value in set:
strValue= str(value)
file.write(strValue+ “n”)
file.close()
•
Given that we already placed the values 1 through 20 in our Numbers.txtfile, we should now have the values 1 through 40 in the file.
a for append
41
Appending to a Non-Existent File
•
If we try to append a file that doesn’t exist, then Python is smart enough to create the file for us, and we can write to it like we’d opened a new file to write to. For example:
file = open(“ThisFileDoesNotExist.txt”, “a”)
set = range(50, 70, 5)
for value in set:
strValue= str(value)
file.write(strValue+ “n”)
file.close()
•
After running the above code, ThisFileDoesNotExist.txtwillnow exist, and contain the numbers 50, 55, 60 and 65 on separate lines.
42
Reading and Writing to a File
•
So far we’ve open a file to read from it or opened a file to write to it.
•
If we tried to read a file opened for writing, or write to a file opened for reading then Python would complain and wouldn’t allow it.
•
But if we wanted to insert data into the middle of the file-so far, the only way we could perform that operation would be to:
1.
Open an existing file for reading,
2.
Open a new file for writing,
3.
Read from the existing file and write that data into the new file until we get to the point we want to insert our new data,
4.
Actually insert our new data into the new file,
5.
Continue copying the rest of our existing file into our new file,
6.
When complete, close and delete our existing file, and finally
7.
Close and rename our new file to the filename of our previously existing file!
•
That seems like a lot of work…
43
Reading and Writing to a File (Cont’d)
•
Instead, let’s use Python’s reading andwriting (“r+”) mode.
•
When doing so, it means we can change our previous lengthy algorithm to insert data to simply be this:
1.
Open an existing file for reading and writing,
2.
Read until we want to insert data,
3.
Insert the data,
4.
Close the file to save the changes.
•
This is obviously a better solution -so let’s see how it’s done!
Work smarter not harder!
44
Reading and Writing to a File (Cont’d)
•
For this exercise, we’ll go back to our Numbers2txt file (which contains the number 1 through 40 on separate lines) and read through it until we get to the number 34, and then we’ll insert the values 34.1 through 34.9 after it, like this:
file = open(“Numbers.txt”, “r+”)
set = range(1, 10)
for line in file:
if (line == “34”):
for value in set:
file.write(line + “.” + str(value) + “n”)
file.close()
•
This looks like it should work… let’s try it out and see!
r+ for read and write
45
Reading and Writing to a File (Cont’d)
•
Bah! Another setback -it did nothing! =(
•
The problem we have here is that when we specify for line in file:,Python doesread each line of the file… but that’s not all it reads.
•
Each time it reads a line and gets a value like 34 -it doesn’t just see “34”, it sees “34n”!
•
That is -it sees the newline character as well! So when we compare our match-value “34”to “34n”it doesn’t match -because they’re not identical!
•
We can fix this in one of two ways:
•
We can either change our search term to look for “34n”, or
•
We can strip off the “n”part.
•
Both of these options will work, but as we’re going to be doing more file manipulation down the line, it’s worth knowing how to strip off the newline characters and get at the ‘raw’ line data without any formatting characters.
46
Reading and Writing to a File (Cont’d)
•
Why don’t we try to strip off the “n” part of the line as a substring?
file = open(“Numbers.txt”, “r+”)
set = range(1, 10)
for line in file:
newlineStart= line.find(“n”)
rawLine= line[:newlineStart]
if (rawLine== “34”):
for value in set:
file.write(rawLine+ “.” + str(value) + “n”)
file.close()
•
We’ve already failed once -but we’re making progress… So do you think thiswill work? It seems to make sense…
Find location of newline character in line
Create a ‘raw’ version which doesn’t contain it
Now compare against the ‘raw’ version!
47
Reading and Writing to a File (Cont’d)
•
It does find a match, and it does insert data… but it inserts it at the end of the file, like this:
•
That’s not what we wanted, so it’s back to the drawing board for us….
48
Successful Data Insertion or Bust!
•
It turns out that you simply cannotdirectly insert data into the middle of an existing file due to filesystemconsiderations (i.e. FAT32, NTFS, Ext3, Ext4, Btrfsetc. -if these terms mean nothing to you then please don’t worry about them!)
•
To put it quite simply, you can never just growa file to make it larger and contain more data… but we CAN grow the set of lines read from a file, and then write that ‘new’ set back over the top of the original file…
•
So let’s nail it this time and be done with it…
49
Successful Data Insertion or Bust! (Cont’d)
•
The following code will copy the contents of Numbers.txtinto a new file called FinalNumbers.txtand insert our desired values:
source = open(“Numbers.txt”, “r”)
dest= open(“FinalNumbers.txt”, “w”)
set = range(1, 10) # 0 through 9
for line in source:
newlineLoc= line.find(“n”)
rawLine= line[:newlineLoc]
if (rawLine== “34”):
dest.write(line) # Copy 34 to dest
for value in set: # Add our 34.1 up to 34.9
dest.write(rawLine+ “.” + str(value) + “n”)
else:
dest.write(line)
source.close()
dest.close()
50
Successful Data Insertion or Bust! (Cont’d)
•
Got it! With that done, the only thing left to do is to delete our Numbers.txt file, and rename our FinalNumbers.txt file to Numbers.txt!
•
To do this, after the code on the previous slide we have to import some additional functionality into our Python script, and use the remove and rename functions, like this:
import os;
os.remove(“Numbers.txt”)
os.rename(“FinalNumbers.txt”, “Numbers.txt”)
51
Wrap up
•
We’ve covered a lot of ground this class, such as:
•
Multiplying strings,
•
Finding substrings and their locations within existing strings,
•
Converting strings to list and back + stripping whitespace,
•
Casting between types, and
•
File handling, including:
•
Reading (r),
•
Writing (w),
•
Appending (a), and
•
Reading+writing(r+).
•
You’ll get a chance to experiment with all these techniques in this week’s lab!
The post Week 4 -Strings, Substrings and Files appeared first on My Assignment Online.