3_2_8 String handling operations in a programming language

You should be able to:

  • Understand and be able to use:

•• length

•• position

•• substring

•• concatenation

•• convert character to character code

•• convert character code to character

•• string conversion operations.

REVISE:

PLEASE NOTE:

I have used the print() function a lot in these examples. This is because a student running the code would most likely be using it in an application. The print function allows the programmer to SEE what is happening with the piece of code that they are using. The print function can then be removed when used with the application.

Length

To determine the length of string in Python use the code:

myVar = "HELLO"
print (len(myVar))

To determine the length of an array in Python use the code:

myArray = ["one","two","three"]
print (len(myArray))

The function that we are using here is len()

You can use this function when you need to determine the length of an object.

In a practical example you might use len() to show the number of letters in a word that a player needs to guess.

wordLength = (len(word))
print ("Guess a word with "+str(wordLength)+" letters")

Position

To find a letter in a variable you can use:

word = "hello"
print (word[0])

To find an item in an array you can use:

myArray = ["one","two","three"]
print (myArray[1])

The syntax being used here is a square bracket that is linked to a variable or array name. The number in the square bracket determines the location that you wish to find (in Python this always starts with a 0). This number could also be a variable.

toFind=int(input("Which item would you like to find?"))
print (myArray[toFind])

We can also do the opposite and find a particular letter in a word.

myVar = "HELLO"
print (myVar.index("H"))

And the same for an item in an array.

myArray = ["one","two","three"]
print (myArray.index("two"))

The array or variable name is followed by .index() and then the item that you wish to find is placed inside the brackets.

Substring

Substring is taking a slice or a part of the string or array.

In Python we use the slice syntax.

myVar = "HELLO"
print (myVar[1:3])

This would only print "EL" because we are looking at a range and range doesn't include the last value.

To print everything but the first letter we could do.

myVar = "HELLO"
print (myVar[1:])

To print only the first letter we could do.

myVar = "HELLO"
print (myVar[:1])

Concatenation

Concatenation is just joining two or more strings together.

firstname="Tanya"
surname="Hardwick"
print (firstname+surname) #this is the concatenation

When we use the + symbol between two variable names we are concatenating the string. This would print as TanyaHardwick because we haven't told the code to add a space in between.

We cannot concatenate string and numbers together without using some extra syntax. If I wanted to automatically create a username for Tanya Hardwick then I would need to do this...

firstname="Tanya"
surname="Hardwick"
year = 2017
username=(firstname+surname+str(year))
print (username)

Note that the year variable was converted to string to match the data types of the other variables.

Convert Character to Character Code

Each character has a decimal number associated with it. This is known as the character code.

To convert a character to its corresponding code we can do this:

character = "C"
print (ord(character))

Convert Character Code to Character

Each character code can be converted back to its corresponding character.

To convert a character code to a character we can do this:

code = 67
print (chr(code))

String Conversion Operations

Revisit 7_3_2

Other Useful Syntax

In these examples s stands for the variable name that contains a string. In my examples above I used myVar instead of s.

  • s.isalpha() - checks if the letter is in the alphabet
  • s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
  • s.strip() -- returns a string with whitespace removed from the start and end
  • s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes
  • s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
  • s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
  • s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
  • s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
  • s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

SOURCE: The other useful syntax section is take from here: https://developers.google.com/edu/python/strings This is a great place to look for help with string manipulation.

Programming Challenge:

Create a password encryption program. The user should be able to:

  • Type in a password that contains three random words (they MUST all be letters)
  • The password entered should then be converted to its ASCII decimal number
  • The number should increase by 2 (e.g. A is 65 in decimal so it would now display 67)
  • The encrypted version of the password is displayed to the user

EXTENDING THE PROGRAM (Extra Mile):

  • Can you get it to convert back if the user types in the code?
  • Can you get it to store the encrypted password in a text file?

TEST:

  1. Download and print the test paper here: https://drive.google.com/open?id=0B5fLtQ0Xgr2PamQ4T2h3bzhZMkk
  2. Try the mock test yourself.
  3. Use the 3.2.8 Walking Talking Mock below to guide you through answering the questions.

SOURCE RECOGNITION - PLEASE NOTE: The examination examples used in these walking talking mocks are samples from AQA from their non-confidential section of the public site. They also contain questions designed by TeachIT for AQA as part of the publicly available lesson materials.