CS23 : How long is a piece of string?


In this section, we will be learning some simple skills in the field of string handling. That's it.

We are learning ...
  • Use strings confidently in programming
So that we can ...
  • Determine characteristics of strings
    - Length
    - type of data contained in the string
  • Split strings up and join them together
    - An understanding of position
    - Substrings
    - Concatenation
  • Understand the character encoding methods used in strings
    - Character to character code
    - Character code to character
  • Perform string conversions
    - string, integers, floats, datetime

To be honest, by now, if you can't handle strings you really need to ask yourself what you have been doing all these years! Strings are a fundamental data type - all data 'given' to a computer via the keyboard comes in the form of strings. A string is merely a list of characters and many string operations are the same as the list operations we have met before.

The characters in strings are numbered starting at zero

Activity 1 Basic Python string methods (60)

To be honest, all string operations like this are important. Without altering a string, we can use standard programming commands to find out a little about it.
  1. We can determine the length of a string using the len(string) command.

  2. We can determine what type of characters are in the string using the string.isalpha(), string.isalnum() and string.isdigit() functions.

  3. We can check whether a substring is present within the string using the in keyword.

  4. We can search for the first position of a substring in a string using the string.find(substring) function.

  5. We can count how many times a substring appears in a string using the string.count(substring) command.

  6. We can split up a string using the string.split([delimeter]) command. Without a parameter, the command will do it's best to determine the delimiter (usually a space or a comma).

  7. We can join strings together using the delimiter.join(list) command.

  8. We can join strings together using the concatenation operators, ',' and '+'. They both work in different ways and with different data types - be careful!

  9. We can convert a single character into an ASCII code using the ord() command.

  10. We can convert a single ASCII code into a character using the chr() command.

  11. We can convert string to integers using the int() command.

  12. We can convert strings to decimals using the float() command.

Yes you have!

However, it's worth noting that if you ever did get asked a question about string operations like this in an exam, the questions would not use Python code (unfair!). Instead, they would be in some flavour of pseudocode. For instance ...
  • The find operation would probably look like find(substring,string) instead of string.find(substring)
  • The count operation would probably look like count(substring,string) instead of string.count(substring)
  • The join operation would probably look like join(string,delimeter) instead of delimeter.join(string)
... and so on.

Task 1.1
 Programming reference cards - Finding out about strings

Quick reference cards are great - I wish I had a set for the Python programming language! Your task is to make a start by creating a set of 15 reference cards for Python functions mentioned above ...

len(
string)

string.isalpha()
string.isalnum()
string.isdigit()
substring in string
string
.find(substring)
string.count(substring)
string.split()
delimiter.join(list)
print(string + string)
print(string , string)
ord(character)
chr(code)
int(string)
float(string)

You can structure your reference cards however you like but they must contain information about the syntax of the command and three examples of it in use. You might want to use the Python Strings section at Tutorialspoint to help you.

OUTCOME : Set of reference cards for Python programming.


One of the most common string operations is called string slicing which can be used to return parts of a string. We use colons (:) to separate the starting and ending indices from the string. For example ...

string[start:end+1 returns a substring starting at start and ending at the end
string[start:]       returns a substring starting at start to the end of the string
string[:end+1]       returns a substring from the start of the string, ending at end
string[:]            returns the whole string

Be careful - you must always add one to the end character index or you will miss off the last character.

Task 1.2 
 String slicing

Consider the following string ... "This is an example of string slicing"

In your notebooks : Write suitable string slices in order to return ...
  • 'example'
  • 'string'
  • ' of '
  • 'is an'
  • 'This'
You may want to test out your solutions at the prompt before you commit to paper.

OUTCOME : String slice operations


Activity 2 Date and time (70)

Not really a string manipulation task, per se but still useful to know and certainly essential to know before we look at string / datetime conversions. We'll learn how to work with dates and times in this section. Again, the best way to do this is by using tutorials (although your teacher may demonstrate some stuff to you before you start, if you're lucky!)

Before we learn how to format datetime objects, we need to learn how to work with dates and times in Python. 

Task 2.1
 Working with dates and times

  • Open up the Python programming environment. All the examples here are carried out at the prompt. by typing the suggested commands and pressing the  ENTER  key afterwards. You should evidence what you have done during this activity by writing down the commands you have issued in your notebooks.


    But only for evidence ...

  • You first have to import components of the datetime library because the datetime functions are not built into the standard Python library.

    >>> from datetime import datetime
    >>> from datetime import date
    >>> from datetime import time

    We import the datetime, date and time modules separately to make things easier later on. What's confusing is that the datetime library has it's own datetime module - datetime.datetime if you will - which is confusing, I know. 

  • First, we can create a new object containing the current date and time.

    >>> dt = datetime.now()

  • Let's inspect the format of the datetime object.

    >>> dt

    In your notebooks : You should see a comma separated list of integers as parameters within a datetime object. Can you work out what each of the parameters is? Write down your ideas in a suitable way in your notebooks. (The only one you might struggle with is the last one ...)

  • We can extract the various components of the datetime object. 

    >>> dt.year
    >>> dt.month
    >>> dt.day
    >>> dt.hour
    >>> dt.minute
    >>> dt.second
    >>> dt.microsecond


    Notice that there are no brackets after the end of each command.

  • We could also ask Python what day of the week we are on - nice.

    >>> dt.weekday()

    You should get a number between 0 and 6, where 0 represents Monday and so on. I suppose, we could print the full day name like this ...

    >>> weekdays = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
    >>> weekdays[dt.weekday()]

    ... but we actually don't need to (see later on).

  • We can define our own dates and times to work with as well by declaring suitably resolved datetime objects.

    >>> birthdate = date(1987,7,13)
    >>> birthtime = time(14,12,00)
    >>> birthdatetime = datetime(1970,7,27,14,12,00)

    These methods create a suitable datetime object from a list of relevant components. I can work out what day my birthday was on from ...

    >>> weekdays[birthdate.weekday()]

    Nice. To be honest, the birthtime variable makes no sense on it's own (as we'll see later).

  • Working out the difference between two dates is easily accomplished using a standard subtraction operation. Let's say, for arguments sake, that I want to work out how many days I've been alive for. First, we derive a date object for today ...

    >>> datenow = datetime.date(datetime.now())

    Here, we have used a different method for creating our date object because we are supplying it with an existing datetime object rather than a list of date components so we use datetime.date() instead of date().

    >>> datenow - birthdate

    This gives us a datetime.timedelta() object (time difference) with a parameter which indicates the number of days between the two datetime objects we have provided. Check it and see!

  • Working out the difference between two times is more difficult since (apparently) it makes no sense to calculate time differences (something to do with time zones and midnight or something). Let's create two time objects and work out the difference.

    >>> t1 = time(14,25,13)
    >>> t2 = time(16,45,12)
    >>> t2 - t1

    This should give you an error because, as I've said, times can't directly be compared. However, we can convert the time object into a datetime object using datetime.combine() to put them on the same day ...

    >>> today = datetime.date(datetime.now())
    >>> delta = datetime.combine(today,t2) - datetime.combine(today,t1)
    >>> print(str(delta))

    Right - this should give you a datetime.timedelta() object which tells you the number of days, seconds and microseconds between each time. It's likely that the number of days is 0 (because they are on the same day in this example) and there is no microsecond parameter because we didn't specify the times accurately.

    One application of this is to time how long scripted operations take. Download the timer.py script from the lesson resources and investigate it's operation. Print out a copy for your notes.


OUTCOME : Suitably hand written notes on using a declaring datetime objects.


Now that we know how to handle dates and times (!) let's learn how to convert from strings and datetime objects and vice versa! You never know when it might come in handy!

Great Scott!

Formatting dates and times in Python involves the use of string format specifiers. There is a great reference to these available at http://strftime.org or by clicking the image below (which is from http://strftime.org/ anyways).

https://drive.google.com/file/d/0B83yXMOilskaZXVHRFNPXzhEaWs/view?usp=drive_web
Click to enlarge

There are two functions which we are interested in ...
  • The 'string format time' function : object.strftime(format)
    Takes a time, date or datetime object and formats it based on the format specifier returning a string.

    >>> datetime.today().strftime("%A, %B %d, %Y")
    'Tuesday, February 28, 2017'

  • The 'string parse time' function : datetime.strptime(string,format)
    Takes a string and a format specifier and returns a datetime object.

    >>> datetime.strptime("Tuesday, February 28, 2017","%A, %B %d, %Y")
    datetime.datetime(2017, 2, 28, 0, 0)



Task 2.2 
 Formatting dates and times - string / datetime conversions

My birthday is on the 27th July 1970 (so now you know!)

At the prompt : I would like you to ...
  1. Create a date object for my birthday using strptime() and 
  2. Print it out in 5 different formats using strftime(). 
  3. Job done.
Print out the contents of the console and stick it in your notebooks.

OUTCOME : Evidence that you can convert between datetime objects and strings.


Extension Activities 

How about these?


What's next?

Before you hand your book in for checking, make sure you have completed all the work required and that your book is tidy and organised. Your book will be checked to make sure it is complete and you will be given a spicy grade for effort.

END OF TOPIC ASSESSMENT