Download Python 8: Fun with strings

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
OCR GCSE Computing
Python programming
8: Fun with strings
OCR Computing GCSE
© Hodder Education 2013
Slide 1
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 2
Python 8: Fun with strings
You 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 3
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 4
Python 8: Fun with strings
A few string methods:
OCR Computing GCSE
© Hodder Education 2013
Slide 5
Python 8: Fun with strings
The ‘in’ operator
This 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 6
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 7
Python 8: Fun with strings
You 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 8
Python 8: Fun with strings
Slicing
You 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.
OCR Computing GCSE
© Hodder Education 2013
Slide 9