Session-3 Python Strings
Session-3 Python Strings
Strings
Today’s Topics:
Strings are sequence of Characters.
OR
In Python specifically, strings are a sequence of
Unicode Characters
Creating Strings
Accessing Strings
Adding Chars to Strings
Editing Strings
Deleting Strings
Operations on Strings
String Functions
Creating Strings
a = 'single quote'
b = "double quotes"
# multiline strings
c = '''single quote multiline'''
d = """double quotes multline"""
e = str("type casting")
print(a)
print(b)
print(c)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
print(d)
print(e)
Negative Indexing
s = "hello world"
print(s[-3])
print(s[-13]) # gives error
Slicing
s = "hello world"
print(s[6:0:-2])
Example:
print(s[::-1]) # reverse string
s = "hello world"
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
print(s[-1:-6:-1])
Editing and Deleting in Strings
s = "hello world"
s[0] = 'H'
Operations on Strings
Arithmetic Operations
Relational Operations
Logical Operations
Loops on Strings
Membership Operations
Example:
print("Pune" + " " + "Mumbai")
print("Pune "*10)
print("*"*50)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
"Pune" != "Pune"
"Mumbai" > "Pune"
"Pune" > "pune"
"hello" and "world"
"hello" or "world"
"" and "world"
"" or "world"
"hello" or "world"
"hello" and "world"
not "hello"
Example:
for i in "hello":
print(i)
Example:
for i in "Pune":
print("Pune")
Example:
"P" in "Pune"
Common Functions
len: count length of a string
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
max: check first string is maximum than second
one or not
min: check first string is minimum than second or
not
sorted: sort the characters from given string
sorted(name,reverse=True): descending order
sorting
Example:
len("hello world")
max("hello world")
min("hello world")
sorted("hello world")
sorted("hello world", reverse = True)
Methods:
Capitalize / Title / Upper / Lower / Swapcase
s = "hello world"
print(s)
print(s.capitalize())
#capitalize only initial letter from given string
s.title()
#capitalize initial letter of every word from a given
string
s.upper()
"HeLlO WorLD".lower()
"HeLlO WorLD".swapcase()
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
#convert capital to lowercase and lowercase to
capital case
Count / Find / Index
"Teknowell EduTech Chinchwad".count("e")
"Teknowell EduTech Chinchwad".find("e")
"Teknowell EduTech Chinchwad".find("z")
"Teknowell EduTech Chinchwad".index("e")
"Teknowell EduTech Chinchwad".index("z")#error code
endswith / startswith
"Teknowell EduTech Chinchwad".endswith("e")
"Teknowell EduTech Chinchwad".endswith("d")
"Teknowell EduTech Chinchwad".endswith("ech")
"Teknowell EduTech Chinchwad".endswith("wad")
"Teknowell EduTech Chinchwad".startswith("t")
"Teknowell EduTech Chinchwad".startswith("T")
"Teknowell EduTech Chinchwad".startswith("tek")
"Teknowell EduTech Chinchwad".startswith("Tek")
String Format
age=23
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
name="Surekha"
print("My Name is ",name "and age is ",age)#Normal
Way
print(f"My Name is {name} and age is {age}")#using f
print("My name is {0} and age is
{1}".format(name,age))#using format
Replace
"Teknowell EduTech Chinchwad".replace("Chinchwad",
"Pimpri")
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
"Teknowell EduTech Chinchwad".replace("akgjhl",
"Pimpri")
Example Programs
Find the length of a given string without using the
len() function
s = input("Enter a string: ")
counter = 0
for i in s:
counter += 1
print("Length of given string is =", counter)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Count the frequency of a particular character in
provided string.
Example, "hello how are you" is a string, the
frequency of h in this string is 2.
Using function:
sentence=input('Enter any sentence:')
word=input('Enter any word:')
count=sentence.count(word)
print(count)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
result = result + i
print(result)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
temp += i
else:
L.append(temp)
temp = ""
L.append(temp)
print("Splited string :", L)
print("Number of words in given string is :", len(L))
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
print(type(result))
Time Complexity:
Techniques to measure time complexity
Measuring Time to execute
Counting operations involved
Abstract notion of order of growth
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
What is the meaning of Time varies if implementation
changes use the below code:
Here instead of for I’m using while see the time is
different.
import time
start=time.time()
i=1
while(i<=100):
i=i+1
end=time.time()
print(end-start)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
What do we want?
1.We want to evaluate the algorithm
2.We want to evaluate scalability(how it behaves
for big inputs)
3.We want to evaluate in terms of input size(built
the mathematical relationship between the input
and time taken by the program)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Orders of Growth(This technique mostly used in
industry)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
In above
answer=1 is first operation----------it is outside of
loop
So, Count:1+5n+1--------5n+2
Five operations performs multiple times
Ignore additive constant that is 2
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Ignore multiplicative constant that is 5.
So,
Time complexity of above program is O(n).
Output-1:
Output-2:
Output-3:
Output-4:
Output-5:
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Constant:
Quadratic:O(n^2)
Nested loop
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Logarithmic:(n)
Increase input time decreases.
Example:
Binary search
Exponential:(O(2^n)):
Input increase time also increases but its in a high
amount.
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
If both the for loops are same then use below
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Example:
number = int(input('enter the number'))
digits = '0123456789'
result = ''
while number != 0:
result = digits[number % 10] + result
number = number//10
print(result)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Example:
L = [1,2,3,4]
sum = 0
for i in L:
sum = sum + i
product = 1
for i in L:
product = product*i
print(sum,product)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Example:
A = [1,2,3,4]
B = [5,6,7,8]
for i in A:
for j in B:
print(i,j)
Example:
A = [1,2,3,4]
B = [5,6,7,8]
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
for i in A:
for j in B:
for k in range(1000000):
print(i,j)
Example:
L = [1,2,3,4,5]
for i in range(0,len(L)//2):
other = len(L) - i -1
temp = L[i]
L[i] = L[other]
L[other] = temp
print(L)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Here number of operations are 4.
len(L)/2
n/2
Example:
n = 10
k = 0;
for i in range(n//2,n):
for j in range(2,n,pow(2,j)):
k = k + n / 2;
print(k)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Example:
a = 10
b = 3
if b <= 0:
print(-1)
div = a//b
print(a-div-b)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Example:
n = 345
sum = 0
while n>0:
sum = sum + n%10
n = n // 10
print(sum)
Example:
def fib(n):
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
if n == 1 or n == 0:
return 1
else:
return fib(n-1) + fib(n-2)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Example:Subset Algo
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Example:
{3T(n-1) if n>0
T(n) = {1, otherwise
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Example:
{2T(n-1)-1 if n>0
T(n) = {1, otherwise
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Week-1 Interview Questions
1.What is Python? What are the benefits of using
Python?
2.What is a dynamically typed language?
3.What is an Interpreted language?
4.What is PEP 8 and why is it important?
5.What are the common built-in data types in
Python?
6.Explain the ternary operator in Python.
7.What Does the ‘is’ Operator Do?
8.Disadvantages of Python.
9.How strings are stored in Python?
10.What is Zen of Python?
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
11.Identity operator (is) vs ==?
12.What does _ variables represent in Python?
13.Modules vs packages vs Library
14.Why 0.3 – 0.2 is not equal to 0.1 in Python?
15.Python Docstrings
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Before we understand a dynamically typed language, we
should learn about what typing is. **Typing** refers
to type-checking in programming languages. In a
**strongly-typed** language, such as Python, **"1" +
2** will result in a type error since these languages
don't allow for "type-coercion" (implicit conversion
of data types). On the other hand, a **weakly-typed**
language, such as Javascript, will simply output
**"12"** as result.
Read more -
https://www.techtarget.com/whatis/definition/strongly
-typed#:~:text=In%20computer%20programming%2C%20a
%20programming,types%20of%20objects%20and
%20variables.
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
4. What is PEP 8 and why is it important?
PEP stands for Python Enhancement Proposal. A PEP is
an official design document providing information to
the Python community, or describing a new feature for
Python or its processes. **PEP 8** is especially
important since it documents the style guidelines for
Python Code. Apparently contributing to the Python
open-source community requires you to follow these
style guidelines sincerely and strictly.
Read more -
https://realpython.com/python-pep8/#:~:text=PEP
%208%2C%20sometimes%20spelled%20PEP8,and
%20consistency%20of%20Python%20code.
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
numbers. Additionally, booleans are a sub-type of
integers.
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
https://www.programiz.com/python-programming/
precedence-associativity
a,b=2,3
min=a if a<b else b
print(min)
Identity operators<br>
In Python, is and is not are used to check if two
values are located on the same part of the memory.
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Two variables that are equal does not imply that they
are identical.
a is b
id(a)
id(b)
a = 257
b = 257
a is b
id(a)
a == b
id(b)
a = -14
b = -14
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
a is b
Q 9: Disadvantages of Python.
https://www.geeksforgeeks.org/disadvantages-of-python
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
* Sparse is better than dense.
* Readability counts.
* Special cases aren't special enough to break the
rules.
* Although practicality beats purity.
* Errors should never pass silently.
* Unless explicitly silenced.
* In the face of ambiguity, refuse the temptation to
guess.
* There should be one-- and preferably only one --
obvious way to do it.
* Although that way may not be obvious at first
unless you're Dutch.
* Now is better than never.
* Although never is often better than *right* now.
* If the implementation is hard to explain, it's a
bad idea.
* If the implementation is easy to explain, it may be
a good idea.
* Namespaces are one honking great idea -- let's do
more of those!
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
->> Here’s the main difference between python “==” vs
“is:”
# Case 4:
# Here variable s is assigned a list,
# and q assigned a list values same as s but on
slicing of list a new list is generated
s=[1,2,3]
p=s
# cloning:
q=s[:]#-this is called as cloning means store data on
different location
print("id of p", id(p))
print("Id of s", id(s))
print("id of q", id(q))
print("Comapare- s == q", s==q)
print("Identity- s is q", s is q)
print("Identity- s is p", s is p)
print("Comapare- s == p", s==p)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
a=[1,2,3]
b=a
a.append(4)
print(a)
print(b)
a = [1,2,3]
b = a[:]#this is called as cloning means store data
on different location
a.append(4)
print(a)
print(b)
[GssksForGeeks
Article](https://www.geeksforgeeks.org/underscore-_-
python)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Ignore a value when unpacking
print("x-",x)
print("y-", y)
for _ in range(5):
print('hello')
https://stackoverflow.com/questions/19198166/whats-
the-difference-between-a-module-and-a-library-in-
python
https://www.geeksforgeeks.org/what-is-the-difference-
between-pythons-module-package-and-library/
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
Q15 Why 0.3 – 0.2 is not equal to 0.1 in Python?
https://www.geeksforgeeks.org/why-0-3-0-2-is-not-
equal-to-0-1-in-python/
# code
print(0.3 - 0.2)
print(0.3 - 0.2 == 0.1)
Q 16 - Python Docstrings
https://www.geeksforgeeks.org/python-docstrings
print('hello')
type(3)
print(type.__doc__)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.
~(3)
s="have"
print(s)
s.capitalize()#changes not done in original, it
creates new string
print(s)
s = 'have'
print(id(s))
s = s.capitalize()
print(id(s))
print('hello'),print('world')
a,b = print('hello'),print('world')
print(a,b)
Office No-77,5th Floor, Kunal Plaza, Old Mumbai-Pune Highway, Chinchwad, Pune.