Python Lecture 4-Python-Strings
Python Lecture 4-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
first = “krsd”
last=“ing”
king
ring
sing
ding
Strings
• Slicing
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
fruit = Watermelon
print (fruit.find(“m”))
à5 (found at forward index)
print (fruit.find(“g”))
à-1 (is not found)
word1 = “hello”
word2 = “yellow”
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.