Python:Strings
Strings
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Strings
• String is a sequence of characters (case
sensitive)
fruit = ‘banana’
• len() is a function that gives the length of
the string
– len(fruit) -> 6
• Can compare strings using ==, >, <
Strings
• Square brackets are used to perform indexing into a string
to get the value at certain index/position
– fruit=“banana”
– fruit[0] -> “b”
– fruit[1] -> “a”
– fruit[2] -> “n” Forward Indexing
– fruit[3] -> “a”
– fruit[4] -> “n”
– fruit[5] -> “a”
Strings
• Square brackets are used to perform indexing into a string
to get the value at certain index/position
– fruit=“banana”
– fruit[-1] -> “a” last element at index -1 (n-1)
– fruit[-2] -> “n”
– fruit[-3] -> “a” Reverse Indexing
– fruit[-4] -> “n”
– fruit[-5] -> “a”
– fruit[-6] -> “b”
Strings
• For Loop in string
– for i in range(0, len(fruit),2):
print (fruit[i])
b
n
n
for letter in fruit:
print (letter)
b
a
n
a
n
a
Strings
• For Loop in string
first = “krsd”
last=“ing”
for letter in first:
print (letter+last)
king
ring
sing
ding
Strings
• Slicing
[start, stop, step]
[start, stop] then step = 1 (default)
s = “abcdefgh”
s[3:6] will give “def”
s[3:6:2] will give “df”
s[::] will give “abcdefgh”
s[::-1] will give “hgfedcba”
fruit = “watermelon”
print (fruit[:5]) à will give “water”
Print (fruit[5:]) à will give “melon”
Strings
• Methods
To convert to uppercase (capital) letters
s = “abcdefgh”
capital_s = s.upper()
print (capital_s)
à ABCDEFGH
If the letter is lower case or not
fruit = Watermelon
if fruit[0].islower():
print (“The first letter is not a capital”)
else
print (“The first letter is a capital”)
Strings
• Methods
Find letter in a string
fruit = Watermelon
print (fruit.find(“m”))
à5 (found at forward index)
print (fruit.find(“g”))
à-1 (is not found)
print (fruit.find(“e”,4)) (starts search for e from index 4)
à6
Strings
• Comparison
==, >, <, etc. (alphabetical order)
word1 = “hello”
word2 = “yellow”
if (word1 < word2):
print (word1 + ’ comes before ‘ + word2)
else:
print (word2+ ‘ comes before ‘ + word1)
Strings
• Strings are immutable i.e., they can not be changed. It can
be sliced and concatenated.
word1 = “hello”
word1[0]=‘y’ Not Possible!
word2 = word1[1:len(word1)]
word2 = ‘y’+word2
Strings
Exercises
• 1. Given two words print the longer word.
2. Count number of common letters in two words
3. Count number of words in a given string.
4. Given a word, get another word where all
'e's are replaced by 'i'.
5. Given a word, print it so that the first letter is in upper case form
(Capital letter)
6. Write a function which returns True if given word contains the
letter ‘e’, else it returns False.