ocr computing gcse © hodder education 2013 slide 1 ocr gcse computing python programming 8: fun...
TRANSCRIPT
OCR Computing GCSE © Hodder Education 2013 Slide 1
OCR GCSE Computing
Python programming8: Fun with strings
OCR Computing GCSE © Hodder Education 2013 Slide 2
Python 8: Fun with strings
A string is a sequence of characters.A string is a Python object.As such it has methods.A string is given in quotes:
‘This is a string’
OCR Computing GCSE © Hodder Education 2013 Slide 3
Python 8: Fun with stringsYou can use arithmetic operators on strings.Concatenation is the joining of strings.Use the + operator to join strings.Use the * operator to make multiple copies of strings.
OCR Computing GCSE © Hodder Education 2013 Slide 4
Python 8: Fun with strings
Strings have ‘methods’. This is the built-in things that they can do.
Methods of objects are referenced by the ‘dot’ notation.
For example, to make a string upper case, use the upper method.
string.upper()
Notice the brackets in case you need to add arguments.
Remember: Strings are immutable. This means once they have been created, they cannot be changed. But, you can copy them and examine them.
OCR Computing GCSE © Hodder Education 2013 Slide 5
Python 8: Fun with stringsA few string methods:
OCR Computing GCSE © Hodder Education 2013 Slide 6
Python 8: Fun with strings
The ‘in’ operatorThis useful Python operator can check if something is in a sequence, e.g. a string, a list or a tuple. It saves writing a lot of searching code.
OCR Computing GCSE © Hodder Education 2013 Slide 7
Python 8: Fun with strings
Indexing strings
Each letter (character) in a string has a numbered position. We can demonstrate this in the following program:
This program finds the length of a word that is input, then iterates through the word printing each letter in turn on a new line.
OCR Computing GCSE © Hodder Education 2013 Slide 8
Python 8: Fun with stringsYou can access any letter in a word by using its index. Remember that Python starts counting at 0. So, the first letter of ‘word’ is word[0]. You can use negative numbers to count back from the last letter, so word[-1] is the last letter.
So, suppose word=‘hello’
word[0] is ‘h’word[1] is ‘e’
OCR Computing GCSE © Hodder Education 2013 Slide 9
Python 8: Fun with strings
SlicingYou can access a portion of a string.You are not restricted to one letter at a time.You just need to specify the start position and the end position.You can use positive or negative positions, or a mixture of the two.