COL100 �Introduction to Computer Science
Lecture 17 – Strings
February, 2025
Semester II
2024-2025
Vireshwar Kumar, Aaditeshwar Seth
CSE@IITD
Strings
hi = "hello there"
2
Concatenate Strings
hi = "hello there"
name = "ana"
greeting = hi + " " + name
# “hello there ana "
3
Type Casting Strings
stringNum = “5“
print(type(stringNum))
intNum = int(stringNum)
print(type(intNum))
4
String as an Array of Characters
fruit = “banana”
print(len(fruit)) #6
5
Forward Indexing
6
Backward Indexing
7
Looping through String
fruit = “banana”
for i in range(0,len(fruit)):
print (fruit[i])
fruit = “banana”
for letter in fruit:
print (letter)
first = “krsd”
last=“ing”
for letter in first:
print (letter+last)
8
Slicing Strings
fruit = “watermelon”
print(fruit[:5]) # “water”
print(fruit[5:]) # “melon”
s = “abcdefgh”
print(s[3:6]) # “def”
print(s[3:6:2]) # “df”
print(s[::]) # “abcdefgh”
print(s[::-1]) # “hgfedcba”
9
Methods for Strings
s = “abcdefgh”
capital_s = s.upper()
print(capital_s)
fruit = "Watermelon"
if fruit[0].islower():
print (“The first letter is not capital”)
else:
print (“The first letter is capital”)
10
Find Method
fruit = ”watermelon"
print(fruit.find(“m”))
print(fruit.find(“g”))
print(fruit.find(“e”,4))
11
String Comparions
s1 = “acol100”
S2 = “acol100”
print(S1 == s1)
word1 = “hello”
word2 = “yellow”
if (word1 < word2):
print (word1 + ’ comes before ‘ + word2)
else:
print (word2 + ‘ comes before ‘ + word1)
12
Strings are Immutable
word1 = “hello”
word1[0]=‘y’ # error
word2 = word1[1:len(word1)]
word2 = ‘y’+word2
13
Additional examples
14