Module 1 - String
Module 1 - String
WITH PYTHON
Strings
A string is a sequence of zero or more characters.
Each character in the string occupies one byte of memory.
Last character is always \0 (null character) – indicates the end
of the string.
Every character in the string is numbered or indexed (null
character is not numbered since it only indicates the end of
the string).
Empty string can be created in order to initialise a variable.
Sample indexing of the string “Hello World” is provided in the
figure.
len() – to know the length of the string
String – subscript operator
To print a single character out of the string
Also called bracket operator
Python allows negative subscript values
[ ] operator cannot be used on the left side of an assignment
operator to change the character of a string.
>>> a = ‘fruit’
>>> c = 3
>>> r = a * c
>>> print(r)
fruitfruitfruit
String – Operations -Slicing
Slicing – to extract a substring out of a given string
The operator [n:m] returns part of the string starting a
position n and ending at position m-1
>>> a = “Emilin”
>>> print(a[ : :-1])
‘nilimE’ #Starts at the end and walks backward
String Comparison
Used to compare strings
String – in operator
in is a Boolean operator that takes two strings and returns
True if the first appears as a substring in the second and False
otherwise.
String module
Traversing a string
To process one character at a time
From left end to right end
Using while loop: Using for loop: