2. A string is a sequence
• A string is a sequence of characters. You can access
the characters one at a time with the bracket operator.
• Ex:
>>> fruit = 'banana'
>>> letter = fruit[1]
>>> print letter
a
3. Contd..
• You can use any expression, including variables and
operators, as an index, but the value of the index has
to be an integer. Otherwise you get:
• Ex:
>>> letter = fruit[1.5]
TypeError: string indices must be integers, not float
4. When the above code is executed, it produces the following result
Contd..
5. Updating Strings
• You can "update" an existing string by (re)assigning a variable to
another string.
• The new value can be related to its previous value or to a
completely different string altogether.
9. len
• len is a built-in function that returns the number of
characters in a string.
• Ex:
>>> fruit = 'banana'
>>> len(fruit)
6
• To get the last character we can use as following.
11. Traversal with a for loop
• Traversal: Start at the beginning, select each character in
turn, do something to it, and continue until the end.
• Ex:
index = 0
while index < len(fruit):
letter = fruit[index]
print (letter)
index = index + 1
12. Contd..
• Another way to write a traversal is with a for loop:
• Ex:
for char in fruit:
print (char)
• Ex2: Write a function that takes a string as an
argument and displays the letters backward, one per
line.
13. Contd..
• Ex:
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print (letter + suffix)
14. String slices
• A segment of a string is called a slice.
• Ex:
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python
15. Contd..
• The operator [n:m] returns the part of the string
from the “n-eth” character to the “m-eth” character,
including the first but excluding the last.
• If you omit the first index (before the colon), the
slice starts at the beginning of the string.
• If you omit the second index, the slice goes to the
end of the string:
16. Contd..
• Ex:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana‘
• If the first index is greater than or equal to the second the
result is an empty string, represented by two quotation
marks.
17. Contd..
• Ex:
>>> fruit = 'banana'
>>> fruit[3:3]
‘ ‘
• An empty string contains no characters and has
length 0
18. Strings are immutable
• It is tempting to use the [] operator on the left side of an
assignment, with the intention of changing a character in
a string. For example:
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
• The reason for the error is that strings are immutable,
which means you can’t change an existing string.
20. Searching
• Traversing a sequence and returning when we find
what we are looking for—is called a search.
• Ex:
def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
21. Contd..
• Ex: Modify find so that it has a third parameter, the
index in word where it should start looking.
def find(word, letter, index):
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
22. Looping and counting
• The following program counts the number of times the
letter a appears in a string:
• Ex:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print count
23. Contd..
• Ex2:Encapsulate this code in a function named
count, and generalize it so that it accepts the string
and the letter as arguments.
25. • Ex3:Rewrite this function so that instead of
traversing the string, it uses the three parameter
version of find from the previous section.
26. String Methods
• S.lower() and S.lower(): Returns the lowercase and upper case
version of the string. The .upper() and .lower() string methods
are self-explanatory.
• Performing the .upper() method on a string converts all of the
characters to uppercase, whereas the lower() method converts all
of the characters to lowercase.
29. Split
• At some point, you may need to break a large string down into smaller
chunks, or strings. This is the opposite of concatenation which merges
or combines strings into one. To do this, you use the split function.
• S.split('delim') : Split() splits or breakup a string and add the data to a
string array using a defined separator.
• If no separator is defined when you call upon the function, whitespace
will be by default. In simpler terms, the separator is a defined character
that will be placed between each variable.
31. JOIN
• s.join(list): The method join () returns a string in which the
string elements of sequence have been joined by str
separator. Opposite of split(),joins the elements in the
given list together using the string as the delimiter.
• Syntax
•
35. Reversing String
• By using the reversed function, you can reverse the string.
• Ex:
str=“banana”
str1=“ ”.join(reversed(str))
print(str1)
Or
str="Pine Apple"
str1=str[::-1]
print(str1)
37. Contd…
String function Operation
str.isalpha() Return true if str contain all letters
str.isdigit() Return true if str contain all digits
str.islower() Return true if str contain all small
letters
str.isupper() Return true if str contain all
uppercase letters
str.replace(w,t) Replace all occurrences of w with t.
str.strip(w) Remove the starting or ending
letters of str
38. Contd..
Function Operation
s.count(char) Return count of char in s
s.index(char) Return index of char in s
min(s) Return min character in s
max(s) Return max character in s
s==w comparison
39. The in operator
The word in is a boolean operator that takes two strings
and returns True if the first appears as a substring in
the second.
Ex:
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
40. Contd..
• Ex:
if char not in 'ABCDEFG':
print('Invalid musical note character found')
if char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(‘Capital letter')
if char in 'abcdefghijklmnopqrstuvwxyz'
print(‘Small letter')
if char in '0123456789‘
print(‘Digit')
41. String comparison
• The relational operators work on strings.
• Ex:
if word < 'banana':
print 'Your word,' + word + ', comes before banana.'
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.'
else:
print 'All right, bananas.'