Professional Documents
Culture Documents
Lect-06 Strings
Lect-06 Strings
Dr.Harish D. Gadade
Strings in Python
● Python String ● Immutable Strings
● Index[] Operators
● Slicing of String
● Traversing a String
2
Prof. Harish D. Gadade, COEP Technological University, Pune
Python Strings
● Characters are building blocks of Python.A word is composed of a
sequence of characters, when a sequence of characters are grouped
together, a meaningful string is created, thus a string is a sequence
of characters treated as a single unit.
● In many programming languages, strings are treated as array of
characters but in Python, a string is an object of the str class.
● String has many constructors.
3
Prof. Harish D. Gadade, COEP Technological University, Pune
String Class
● Strings are the object of the str class.
● When we create a string using the constructor of str class as
s1=””
s2=”I Like Python Programming”
4
Prof. Harish D. Gadade, COEP Technological University, Pune
Basic Inbuilt Python Functions
● Python has several basic inbuilt functions that can be used with
strings.
● len(), min(), max()
s=”PYTHON”
print(len(s))
print(min(s))
print(max(s))
5
Prof. Harish D. Gadade, COEP Technological University, Pune
Index[] Operator
● As a string is a sequence of characters, the characters in a string
can be accessed one at a time through the index operators.
● The first character of the string is stored at 0th index and last
will be stored at a position one less than that of length of the
strings.
● We can also use negative indexing to access the string
6
Prof. Harish D. Gadade, COEP Technological University, Pune
Index[] Operator
7
Prof. Harish D. Gadade, COEP Technological University, Pune
String Slicing
● We can return a range of characters by using the slice syntax.
● Specify the start index and the end index, separated by a colon, to
return a part of the string.
# Slicing
s="I LOVE PYTHON"
print(s[:6])
print(s[:])
print(s[::-1])
print(s[-1:-7:-1])
8
Prof. Harish D. Gadade, COEP Technological University, Pune
Traversing String with for and
while loop
● A programmer can use the for loop and while loop to traverse string as
9
Prof. Harish D. Gadade, COEP Technological University, Pune
Immutable strings
● Strings are immutable sequence of characters.
s="PYTHON"
s[0]="T"
print(s)
10
Prof. Harish D. Gadade, COEP Technological University, Pune
String Operators: +, *, in, not in
● The + operator used to concatenate two strings
s1="PYTHON"
s2="PROGRAMMING" PYTHONPROGRAMMING
print(s1+s2)
11
Prof. Harish D. Gadade, COEP Technological University, Pune
String Operators: +, *, in, not in
● In and not in operators are used to check whether a string is present
in another string or not
12
Prof. Harish D. Gadade, COEP Technological University, Pune
String Comparisons
● String Comparison: ==, <, >, <=, >= !=
s1="PYTHON"
s2="PUNE" False
print(s1==s2) True
print(s1>s2) python
True
print(s1.lower())
print(s1!=s2)
13
Prof. Harish D. Gadade, COEP Technological University, Pune