Python Notes
Python Notes
6. Functions
1. Function with arguments In Python
2. All builtin functions
3. Lambda Functions(map, filter & reduce)
7. Object-Oriented Approach
1. Class, Object & Method.
2. Inheritance in python
3. Polymorphism in python
4. Encapsulation in python
5. Data Abstraction in python
6. Data Hiding & Object Printing
7. Constructors Destructors in Python
8. Garbage Collection in Python
8. Exception Handling
1. Python Exception Handling
2. User-defined Exception
3. Built-in Exception
4. Python Try Except
What is programming...?
Programming is a way for us to tell computers what to do. Computer is a very dumb machine
and it only does what we tell it to do. Hence, we learn programming and tell computers to do
what we are very slow at - computation. If I ask you to calculate 5+6, you will immediately say
11. How about 23453453 X 56456?
What is Python?
Features of Python
What is IDE..?
Hello World
Comments :
A comment is a part of the coding file that the programmer does not want to execute, rather the
programmer uses it to either explain a block of code or to avoid the execution of a specific part
of code while testing.
Single-Line Comments:
Example - 1 :
In [2]: 1 # this is comment so this will note execute
2 print("This is actual code")
Example - 2 :
In [5]: 1 print("This is actual code")# this is comment so this will note execute
Example - 3 :
Multi-Line Comments:
To write multi-line comments you can use ‘#’ at each line or you can use the multiline string.
p is greater than 5.
p is greater than 5.
Escape Sequences :
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:
Input In [24]
txt = "Ramu is the Number "ONE" Person in the world"
^
SyntaxError: invalid syntax
\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
It's ok
In [29]: 1 txt = "This will insert one \\ (backslash)."
2 print(txt)
Print Statement :
The syntax of a print statement looks something like this:
print(object(s), sep=separator, end=end, file=file, flush=flush)
1. object(s): Any object, and as many as you like. Will be converted to string before printed
2. sep='separator': Specify how to separate the objects, if there is more than one. Default is
''
3. end='end': Specify what to print at the end. Default is '\n' (line feed)
4. file: An object with a write method. Default is sys.stdout
Parameters 2 to 4 are optional
In [33]: 1 print("Python")
Python
Rakesh 45 67
END Argument
1
2
3
4
In [36]: 1 # we can use end to make then one line with space seperation
2 for i in range(1,5):
3 print(i,end=" ")
1 2 3 4
1 % 2 % 3 % 4 %
SEP Argument
In [39]: 1 #sep argument is used to seperate the elements with in print function
2 print("rakesh",a,67,sep=" --> ")
In [3]: 1 print(1,2,3,4,end="-->")
1 2 3 4-->
In [5]: 1 print(1,2,3,4,sep="-->")
1-->2-->3-->4
0-->1-->2-->3-->4-->
0
1
2
3
4
In [8]: 1 for i in range(5):
2 print(i,i+1,sep="-->")
0-->1
1-->2
2-->3
3-->4
4-->5
In [41]: 1 f = open("sample.txt","w")
2 for i in [1,2,3,4]:
3 print(i,file=f)
4 f.close()
Flush:
The flush parameter in Python's print function controls whether the output is immediately
flushed or buffered. By default, the print() function buffers the output, which means that it may
not be immediately displayed on the screen or written to a file. However, you can force the
output to be flushed immediately by setting the flush parameter to True.
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
In [2]: 1 a = "Python"
2 b = 200
Variables do not need to be declared with any particular type, and can even change variable
type after they have been set.
In [3]: 1 a = 100 # This is int type
2 b = "Python" # this is STR type
3 print(a,b)
100 Python
Example
In [5]: 1 x = 5
2 y = "John"
3 print(type(x))
4 print(type(y))
<class 'int'>
<class 'str'>
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
<class 'str'>
<class 'int'>
<class 'float'>
Example
In [8]: 1 a = "John"
2 # is the same as
3 b = 'John'
4 print(a)
5 print(b)
John
John
Case-Sensitive
Variable names are case-sensitive.
In [9]: 1 a = 4
2 A = "Sally"
3 #A will not overwrite a
4 print(a)
5 print(A)
4
Sally
Input In [1]
2Variable = 56
^
SyntaxError: invalid syntax
In [3]: 1 Variable@ = 45
Input In [3]
Variable@ = 45
^
SyntaxError: invalid syntax
Input In [2]
variable name =87
^
SyntaxError: invalid syntax
In [12]: 1 def1 = 10
2 def = 10
Input In [12]
def = 10
^
SyntaxError: invalid syntax
In [10]: 1 class = 10
Input In [10]
class = 10
^
SyntaxError: invalid syntax
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
Snake Case
Each word is separated by an underscore character:
Pascal Case
Each word starts with a capital letter:
10 20 30
Note: Make sure the number of variables matches the number of values, or else you will get
an error.
In [32]: 1 a,b = 10,20,30
2 print(a,b,c)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [32], in <cell line: 1>()
----> 1 a,b = 10,20,30
2 print(a,b,c)
In [34]: 1 a = b = c = 34
2 print(a,b,c)
34 34 34
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
1 2 3
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [36], in <cell line: 2>()
1 lst = [1,2,3]
----> 2 x,y = lst
3 print(x,y)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [37], in <cell line: 2>()
1 lst = [1,2,3]
----> 2 x,y,z,xy = lst
3 print(x,y)
Output Variables
The Python print() function is often used to output variables.
Python is easy
In [39]: 1 a = "Python"
2 b = "is"
3 c = "easy"
4 print(a, b, c)
Python is easy
Python is easy
Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".
30
In the print() function, when you try to combine a string and a number with the + operator,
Python will give you an error:
In [42]: 1 a = 40
2 b = "Python"
3 print(a+b)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [42], in <cell line: 3>()
1 a = 40
2 b = "Python"
----> 3 print(a+b)
The best way to output multiple variables in the print() function is to separate them with
commas, which even support different data types:
In [43]: 1 a = 20
2 b = 30.07
3 c = 34+8j
4 d = "Python"
5 print(a,b,c,d)
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as
global variables.
Global variables can be used by everyone, both inside of functions and outside.
In [64]: 1 a = 10
2 def Sample():
3 print(a+20)
4 Sample()
30
If you create a variable with the same name inside a function, this variable will be local, and
can only be used inside the function. The global variable with the same name will remain as it
was, global and with the original value.
In [3]: 1 a = 10
2 def Sample():
3 a = "Python is king"
4 print(a)
5 Sample()
6 print(a)
Python is king
10
Let's see this way. in local variable if we try to access global variable before creat it.
In [5]: 1 a = 10
2 def Sample():
3 print(a)
4 a = "Python is king"
5 print(a)
6 print(a)
7 Sample()
10
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Input In [5], in <cell line: 7>()
5 print(a)
6 print(a)
----> 7 Sample()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [69], in <cell line: 5>()
3 Var = "This is local keyword"
4 Sample()
----> 5 print(Var)
Also, use the global keyword if you want to change a global variable inside a function.
To change the value of a global variable inside a function, refer to the variable by using the
global keyword:
In [76]: 1 x = 5222
2 print(type(x))
<class 'int'>
1
<class 'int'>
2
<class 'int'>
3
<class 'int'>
False
False
False
False
False
False
False
False
False
In [52]: 1 print(bool(1))
2 print(bool("Python"))
3 print(bool(2.8))
4 print(bool([1,2,4]))
5 print(bool(23+56j))
True
True
True
True
True
1.0
<class 'float'>
2.8
<class 'float'>
3.0
<class 'float'>
In [56]: 1 print(float(complex(34,45j)))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [56], in <cell line: 1>()
----> 1 print(float(complex(34,45j)))
In [57]: 1 print(float([1,2,4]))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [57], in <cell line: 1>()
----> 1 print(float([1,2,4]))
s1
<class 'str'>
2
<class 'str'>
3.0
<class 'str'>
In [62]: 1 print(str([1,2,4]))
2 print(type(str([1,2,4])))
[1, 2, 4]
<class 'str'>
In [64]: 1 print(str((1,2,4,5)))
2 print(type(str((1,2,4,5))))
(1, 2, 4, 5)
<class 'str'>
05. list() ==> It is used to convert any data type to a list type.
In [65]: 1 print(list(34))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [65], in <cell line: 1>()
----> 1 print(list(34))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [66], in <cell line: 1>()
----> 1 print(list(34.7))
In [74]: 1 print(list(True))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [74], in <cell line: 1>()
----> 1 print(list(True))
In [90]: 1 print(list("3445"))
2 print(list("Python"))
3 print(list((1,2,4,5)))
4 print(list({1:2,3:4}))
5 print(list({1,2,2,3,3,4,5}))
In [89]: 1 print(tuple("3445"))
2 print(tuple("Python"))
3 print(tuple([1,2,4,5]))
4 print(tuple({1:2,3:4}))
5 print(tuple({1,2,2,3,3,4,5}))
In [92]: 1 print(set("3445"))
2 print(set("Python"))
3 print(set([1,2,4,5]))
4 print(set({1:2,3:4}))
5 print(set((1,2,2,3,3,4,5)))
{1: 2, 2: 3, 3: 4}
{1: 2, 2: 3, 3: 4}
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [99], in <cell line: 2>()
1 #list of list with more then 2 elements
----> 2 print(dict([[1,2,5],[2,3],[3,4]]))
{1: 2, 2: 3, 3: 4}
{1: 2, 2: 3, 3: 4}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [103], in <cell line: 2>()
1 # set of sets
----> 2 print(dict({{1,2},{1,3},{3,4}}))
In [106]: 1 print(ord("a"))
2 print(ord("A"))
97
65
In [109]: 1 print(chr(97))
2 print(chr(65))
a
A
11.complex ==> This function converts real numbers to complex
number
In [111]: 1 a=1
2 print(type(a))
3 print(a)
4 b=complex(a)
5 print(type(b))
6 print(b)
<class 'int'>
1
<class 'complex'>
(1+0j)
In [113]: 1 a=complex(1,2)
2 b=complex(2,3)
3 c=a+b;print(c)
4 d=a-b;print(d)
(3+5j)
(-1-1j)
In [119]: 1 print(complex(20))
2 print(complex(10.5))
3 print(complex(True))
4 print(complex(False))
5 print(complex("10"))
6 print(complex("10.5"))
7 print(complex(1,-2))
8 print(complex(1,-0))
(20+0j)
(10.5+0j)
(1+0j)
0j
(10+0j)
(10.5+0j)
(1-2j)
(1+0j)
In [121]: 1 print(complex(True,True))
2 print(complex(True,False))
3 print(complex(False,False))
4 print(complex(False,True))
(1+1j)
(1+0j)
0j
1j
1.7 All about Operators..?.?
In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical and arithmetic
operations. In this article, we will look into different types of Python operators.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Identity Operators
6. Membership Operators
7. Ternary Operator
8. Bitwise Operators
% Modulus: returns the remainder when the first operand is divided by the second x%y
Addition of 10 and 2 is 12
Subtraction of 10 and 2 is 8
Multiplication of 10 and 2 is 20
float Division of 10 and 2 is 5.0
floor Division of 10 and 2 is 5
Modulus of 10 and 2 is 0
Power of 10 and 2 is 100
Division Operators
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number
or number at the left is divided by the second number or number at the right and returns the
quotient.
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are
integers. For example:
1.0
5.0
-5.0
10.0
The quotient returned by this operator is dependent on the argument being passed. If any of
the numbers is float, it returns output in float. It is also known as Floor division because, if any
number is negative, then the output will be floored. For example:
In [37]: 1 print(10//3) #3
2 print (-3//2) #-2
3 print (5.0//2) #2
4 print (-5.0//2) #-2
5 print(7//3) #3
6 print(7/3) #3
3
-2
2.0
-3.0
2
2.3333333333333335
P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
For example:
x % 10 -> yields the last digit
x % 100 -> yield last two digits
4
34
234
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
>= Greater than or equal to : True if the left operand is greater than or equal to the right x >= y
<= Less than or equal to : True if the left operand is less than or equal to the right x <= y
In python, the comparison operators have lower precedence than the arithmetic operators. All
False
True
False
True
False
True
and Logical AND: True if both the operands are true x and y
1. Logical not
2. logical and
3. logical or
False
True
False
True
False
In [59]: 1 x = 24
2 y = 20
3 list = [10, 20, 30, 40, 50]
4
5 if (x not in list):
6 print("x is NOT present in given list")
7 else:
8 print("x is present in given list")
9 if (y in list):
10 print("y is present in given list")
11 else:
12 print("y is NOT present in given list")
In [65]: 1 x = 10
2 y = 10
3 z = x
4 print(x is y)
5 print(x is z)
6 print(x is not y)
7 print(id(x))
8 print(id(y))
9 print(id(z))
True
True
False
2770717928016
2770717928016
2770717928016
[1, 2, 3]
True
True
[1, 2, 3]
False
True
It simply allows testing a condition in a single line replacing the multiline if-else making the
code compact.
In [63]: 1 x = 10
2 y = 20
3 min1 = x if x<y else y
4 print(min1)
10
| Bitwise OR x|y
~ Bitwise NOT ~x
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
0
14
-11
14
2
40
0 0 0
0 1 0
1 0 0
1 1 1
Example:
a=10;b=20
ANALYSIS
In [23]: 1 a=10;b=20
2 print(bin(a))
3 print(bin(b))
0b1010
0b10100
In [24]: 1 print(a&b)
bitwise OR ( | )
It takes two bit patterns of equal length.
The result in each position is 0 if both bits are 0,
while otherwise the result is 1 (Any One 1 the Result is 1)
x y x|y
0 0 0
0 1 1
1 0 1
1 1 1
Example :
a = 9;b = 65
ANALYSIS
We declared 2 integers a and b, The binary form of
09 = 00001001 ==> for 1 Byte ==> 8 bits
65 = 01000001 ==> for 1 Byte ==> 8 bits
00001001 & 01000001 01001001 R l i 3
In [25]: 1 a = 9
2 b = 65
3 print(bin(a))
4 print(bin(b))
5 print(0b01001001)
0b1001
0b1000001
73
In [22]: 1 print(a|b)
73
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0
Example:
a = 9;b = 65
ANALYSIS
In [29]: 1 print(bin(9))
2 print(bin(65))
3 print(0b01001000)
0b1001
0b1000001
72
Bitwise complement ( ~ ) :
a = 10 # 10=1010
a << 2; # 40=101000==>Add Two digits right side
a = 10 #10=1010
a >> 2; #2=10==>Remove two digits right side
a<b<c
In Python, there is a better way to write this using the Comparison operator Chaining. The
chaining of operators can be written as follows:
if a < b < c :
{.....}
According to associativity and precedence in Python, all comparison operations in Python have
the same priority, which is lower than that of any arithmetic, shifting, or bitwise operation. Also
unlike C, expressions like a < b < c have an interpretation that is conventional in mathematics.
List of comparison operators in Python:
In [10]: 1 a = 200
2 b = 300
3 c = 40
4
5 if a>b and a>c:
6 print(a)
7 elif b>a and b>c:
8 print(b)
9 elif c>a and c>b:
10 print(c)
300
In [11]: 1 if b<a>c:
2 print(a)
3 elif a<b>c:
4 print(b)
5 elif a<c>b:
6 print(c)
7 else:
8 print("Nothing to do")
300
1) Using %
2) Using {}
Using %:
The formatting using % is similar to that of ‘printf’ in C programming language.
%d ==> integer
%f ==> float
%s ==> string
%x ==> hexadecimal
%o ==> octal
Syntax:
Using {}:
We can format strings with variable values by using replacement operator {} and format()
method.
Syntax:
{} .format(value)
Control_Flow Pic:
Line1
Line2
Line3
In [2]: 1 print("Line1");print("Line2");print("Line3")
Line1
Line2
Line3
In [1]: 1 n = 101
2 if n>100:
3 print("This is more then 100")
4 print("THis always executes")
In [2]: 1 n = 10
2 if n>100:
3 print("This is more then 100")
4 print("THis always executes")
if .. else Statement:-
An else statement can be combined with an if statement. An else statement contains the block
In [6]: 1 n = 101
2 if n>100:
3 print("This is more then 100")
4 else:
5 print("This is less then 100")
6 print("THis always executes")
In [7]: 1 n = 10
2 if n>100:
3 print("This is more then 100")
4 else:
5 print("This is less then 100")
6 print("THis always executes")
Python if...elif...else:-
The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.
In [21]: 1 n = 0
2 if n>100:
3 print("This is more then 100")
4 elif n<0:
5 print("This is negative number")
6 elif n>1000:
7 print("This is more then 1000")
8 else:
9 print("Value is zero")
Value is zero
In general nested if-else statement is used when we want to check more than one conditions.
Conditions are executed from top to bottom and check each condition whether it evaluates to
true or not.
In [23]: 1 num = int(input("Enter a number: "))
2 if num >= 0:
3 if (num == 0):
4 print("ZERO")
5 else:
6 print("Positive number")
7 else:
8 print("Negative number")
Enter a number: 0
ZERO
He can vote
What is a Loop?
A loop is a sequence of instructions that is continually repeated until a certain condition is
reached.
Why Loop?
In a loop structure, the loop asks a question. If the answer requires an action, it is executed.
The same question is asked again and again until no further action is required. Each time the
question is asked is called an iteration.
In [31]: 1 s = "PYTHON"
2 s_iter = iter(s)
3 print(next(s_iter))
4 print(next(s_iter))
5 print(next(s_iter))
6 print(next(s_iter))
7 print(next(s_iter))
8 print(next(s_iter))
P
Y
T
H
O
N
2
3
5
7
Range Function
It generates lists containing arithmetic progression. It returns a list of consecutive integers. The
function has one, two or three parameters where last two parameters are optional. It is widely
used in for loops.
range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'range'>
0
1
2
3
4
5
6
7
8
9
In [5]: 1 print(list(range(10)))
2 print(list(range(10,30)))
3 print(list(range(10,30,5)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29]
[10, 15, 20, 25]
0
1
2
3
4
No items left in list
In [9]: 1 # for with else with break
2 for i in range(5):
3 if i == 4:
4 break;
5 print(i)
6 else:
7 print("No items left in list")
0
1
2
3
NOTE:
if we stop the loop, say with a break statement, then the else suite will not be executed
break
To break out from a loop, you can use the keyword "break".
P
Y
T
H
P
Y
T
H
O
N
Loop Completed
Continue
The continue statement is used to tell Python to skip the rest of the statements in the current
loop block and to continue to the next iteration of the loop.
0
1
2
4
5
Else will execute eveytime in continue
0
1
2
3
4
5
Else will execute eveytime in continue
In [18]: 1 x = 0
2 while x<=5:
3 print(x)
4 x+=1
0
1
2
3
4
5
while and else statement
There is a structural similarity between while and else statement. Both have a block of
statement(s) which is only executed when the condition is true.
In [19]: 1 x=1
2 while x<=5:
3 print(x)
4 x=x+1
5 else:
6 print("loop Finished")
7
1
2
3
4
5
loop Finished
In [20]: 1 a=10
2 while a>0:
3 print("Value of a is",a)
4 a=a-2
5 else:
6 print("Loop is Completed")
7
Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed
In [2]: 1 x = 0
2 while x<6:
3 print(x)
4 x+=1
5 else:
6 print("While completed")
0
1
2
3
4
5
While completed
In [3]: 1 x = 0
2 while x<6:
3 if x == 3:
4 break;
5 print(x)
6 x+=1
7 else:
8 print("While completed")
0
1
2
In [ ]: 1 # This will have infinte loops as we have mentioned continue before incre
2 # when poniter reaches 3 it will keep executing continue there is no incr
3 x = 0
4 while x<6:
5 if x == 3:
6 continue;
7 print(x)
8 x+=1
9 else:
10 print("While completed")
0
1
2
In [1]: 1 x = 0
2 while x<6:
3 x+=1
4 if x == 3:
5 continue;
6 print(x)
7 else:
8 print("While completed")
1
2
4
5
6
While completed
Syntax
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
f [ d it ti i bl ] i [ t dl ] #N t dl
In [26]: 1 for i in range(5):
2 for j in range(5):
3 print(i+j,end=" ")
4 print()
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
PASS KEYWORD
It is used when a statement is required syntactically but you do not want any command or code
to execute.
Why Pass?
It is an empty statement
It is null statement
It results into no operation (NOP)
Input In [35]
^
IndentationError: expected an indented block
In [36]: 1 for i in "PYTHON":
2 pass
Note:
Above we can understand that when we use pass keyword there is no error.
User Input
Python allows for user input.
That means we are able to ask the user for input.
The method is a bit different in Python 3.6 than Python 2.7.
Python 3.6 uses the input() method.
Python 2.7 uses the raw_input() method.
Evaluating expression
Enter expression : 2 + 3 + 5
2 + 3 + 5
In [21]: 1 res = eval(input("Enter expression : "))
2 print(res)
Enter expression : 2 + 3 + 5
10
Output:
3. String and Boolean
Manipulations
1. Python Strings and Inbuilt functions
2. Boolean Variables
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'python' is the same as "python".
You can display a string literal with the print() function:
In [13]: 1 print("python")
2 print('python')
python
python
Concatenation:
when we use + operated between a strings then it act as concatenation and add both string.
Python1Python2
Python1 Python2
String Repetition
In [3]: 1 PyStr="PYTHON"
2 print(PyStr,type(PyStr))
3 PyStr='PYTHON'
4 print(PyStr,type(PyStr))
5 PyStr="""PYTHON"""
6 print(PyStr,type(PyStr))
7 PyStr='''PYTHON'''
8 print(PyStr,type(PyStr))
PYTHON
Machine Leaning
In [4]: 1 #Example-2
2 MyStr="PYTHON"
3 print(MyStr)
4 print(MyStr[-1])
5 MyStr[-1]="R"
6 print(MyStr)
PYTHON
N
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [4], in <cell line: 5>()
3 print(MyStr)
4 print(MyStr[-1])
----> 5 MyStr[-1]="R"
6 print(MyStr)
Example
You can use three double quotes:
Example
Or three single quotes:
Note: in the result, the line breaks are inserted at the same position as in the code.
P
Y
T
H
O
N
String Length
To get the length of a string, use the len() function.
Check String
To check if a certain phrase or character is present in a string, we can use the in keyword.
True
False
Using in an if statement:
"Good" is there
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword
not in.
In [33]: 1 txt ="Good morning master"
2 if "good" not in txt:
3 print("good is not there ")
4 else:
5 print("\"good\" is there")
Slicing:
If our string in "PYTHON" then +ve and -ve indexes will assign like below:
P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
In [14]: 1 #+ve slicing
2 a = "PYTHON"
3 print(a[0])
4 print(a[1])
5 print(a[2])
6 print(a[3])
7 print(a[4])
8 print(a[5])
9 print(a[6])
P
Y
T
H
O
N
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [14], in <cell line: 9>()
7 print(a[4])
8 print(a[5])
----> 9 print(a[6])
N
O
H
T
Y
P
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [15], in <cell line: 8>()
6 print(a[-5])
7 print(a[-6])
----> 8 print(a[-7])
In [16]: 1 print(a[:4])
PYTH
In [17]: 1 print(a[2:])
THON
Negative Indexing
Use negative indexes to start the slice from the end of the string:
In [19]: 1 print(a[-6:-2])
PYTH
In [215]: 1 s = "level"
2 if s == s[::-1]:
3 print("Yess ....")
4 else:
5 print("Noooooo...")
Yess ....
In [216]: 1 s = "Rakesh"
2 if s == s[::-1]:
3 print("Yess ....")
4 else:
5 print("Noooooo...")
Noooooo...
What is difference between ASCII and UNICODE string.?
It is a character encoding standard or format that uses numbers from 0 to 127 to represent
English characters.
ASCII value of "A" is 65
ASCII value of "a"is 97
UNICODE:
chr() and ord() two methods which will provide Charcter based on ASCII value and ASCII value
based on character represntly.
In [22]: 1 print(ord("A"))
2 print(chr(65))
65
A
In [30]: 1 print(ord("అ"))
3077
అ
మ
్
మ
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [45], in <cell line: 5>()
3 print(amma[2])
4 print(amma[3])
----> 5 print(amma[4])
String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like
this:
In [47]: 1 age = 25
2 print(" My age is "+age)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [47], in <cell line: 2>()
1 age = 25
----> 2 print(" My age is "+age)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in the string
where the placeholders {} are:
String Methods
Python has a set of built-in methods that you can use on strings.
Note : All string methods return new values. They do not change the original string until we
asign it to original variable.
All Methods:
S.NO Method Description
04 startswith() Returns true if the string starts with the specified value
05 endswith() Returns true if the string ends with the specified value.
Searches the string for a specified value and returns the position of where it was
07 find()
found
Searches the string for a specified value and returns the position of where it was
08 index()
found
Searches the string for a specified value and returns the last position of where it was
09 rfind()
found
Searches the string for a specified value and returns the last position of where it was
10 rindex()
found
11 join() This method takes all items in an iterable and joins them into one string.
21 replace() This method replaces a specified phrase with another specified phrase.
22 split() Splits the string at the specified separator, and returns a list
23 rsplit() Splits the string at the specified separator, and returns a list
25 title() This method make upper case of starting letter of each word in sentance.
26 zfill() This method adds zeros (0) at the beginning of the string.
27 swapcase() Swaps cases, lower case becomes upper case and vice versa.
29 isalpha() Returns True if all characters in the string are in the alphabet.
30 isascii() Returns True if all characters in the string are ascii characters.
01. capitalize() :
Converts the first character to upper case and rest to lower..!
In [5]: 1 #example -3: See what happens if the first character is a number:
2 s = "25 Is my Age"
3 print(s.capitalize())
25 is my age
02. casefold():
The casefold() method returns a string where all the characters are lower case.
This method is similar to the lower() method, but the casefold() method is stronger, more
aggressive, meaning that it will convert more characters into lower case, and will find more
matches when comparing two strings and both are converted using the casefold() method.
03. count():
string.count(value, start, end)
The count() method returns the number of times a specified value appears in the string.
1
04. startswith():
string.startswith(value, start, end)
The startswith() method returns True if the string starts with the specified value, otherwise
False.
True
True
True
False
True
05. endswith():
string.endswith(value, start, end)
The endswith() method returns True if the string ends with the specified value, otherwise
False.
In [11]: 1 txt = "Hello, welcome to my world."
2 x = txt.endswith(".")
3 print(x)
True
In [12]: 1 #Check if the string ends with the phrase "my world.":
2 txt = "Hello, welcome to my world."
3 x = txt.endswith("my world.")
4 print(x)
True
False
06. expandtabs():
string.expandtabs(tabsize)
The expandtabs() method sets the tab size to the specified number of whitespaces.
tabsize : A number specifying the tabsize. Default tabsize is 8
H e l l o
H e l l o
H e l l o
In [19]: 1 txt = "H\te\tl\tl\to"
2 print(txt)
H e l l o
H e l l o
H e l l o
H e l l o
H e l l o
H e l l o
Finding Substrings:
In PYTHON programming to find sub strings we can use the following 4 methods:
Forward direction:
21.find() 22.index()
Backward direction:
23.rfind() 24.rindex()
07. find():
string.find(value, start, end)
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference is that the
index() method raises an exception if the value is not found. (See example below)
7
In [21]: 1 #Where in the text is the first occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.find("e")
4 print(x)
In [22]: 1 #Where in the text is the first occurrence of the letter "e" when you onl
2 txt = "Hello, welcome to my world."
3 x = txt.find("e", 5, 10)
4 print(x)
In [4]: 1 #If the value is not found, the find() method returns -1, but the index()
2 txt = "Hello, welcome to my world."
3 print(txt.find("q"))
-1
08. index():
string.index(value, start, end)
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
The index() method is almost the same as the find() method, the only difference is that the
find() method returns -1 if the value is not found. (See example below)
In [25]: 1 #Where in the text is the first occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.index("e")
4 print(x)
1
In [26]: 1 #Where in the text is the first occurrence of the letter "e" when you onl
2 txt = "Hello, welcome to my world."
3 x = txt.index("e", 5, 10)
4 print(x)
In [5]: 1 #If the value is not found, the find() method returns -1, but the index()
2 txt = "Hello, welcome to my world."
3 print(txt.index("q"))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [5], in <cell line: 3>()
1 #If the value is not found, the find() method returns -1, but the in
dex() method will raise an exception:
2 txt = "Hello, welcome to my world."
----> 3 print(txt.index("q"))
09. rfind():
string.rfind(value, start, end)
The rfind() method finds the last occurrence of the specified value.
The rfind() method returns -1 if the value is not found.
The rfind() method is almost the same as the rindex() method. See example below.
12
3
In [31]: 1 #Where in the text is the last occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.rfind("e")
4 print(x)
13
In [32]: 1 #Where in the text is the last occurrence of the letter "e" when you only
2 txt = "Hello, welcome to my world."
3 x = txt.rfind("e", 5, 10)
4 print(x)
In [33]: 1 #If the value is not found, the rfind() method returns -1, but the rindex
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
4 print(txt.rindex("q"))
-1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [33], in <cell line: 4>()
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
----> 4 print(txt.rindex("q"))
10. rindex():
string.rindex(value, start, end)
The rindex() method finds the last occurrence of the specified value.
The rindex() method raises an exception if the value is not found.
The rindex() method is almost the same as the rfind() method. See example below.
12
In [35]: 1 txt = "Mi casa, su casa."
2 x = txt.index("casa")
3 print(x)
In [36]: 1 #Where in the text is the last occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.rindex("e")
4 print(x)
13
In [37]: 1 #Where in the text is the last occurrence of the letter "e" when you only
2 txt = "Hello, welcome to my world."
3 x = txt.rindex("e", 5, 10)
4 print(x)
In [38]: 1 #If the value is not found, the rfind() method returns -1, but the rindex
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
4 print(txt.rindex("q"))
-1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [38], in <cell line: 4>()
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
----> 4 print(txt.rindex("q"))
11. join():
The join() method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
Note : When using a dictionary as an iterable, the returned values are the keys, not the
values.
John#Peter#Vicky
In [40]: 1 myDict = {"name": "rakesh", "country": "india","age":25}
2 mySeparator = " "
3 x = mySeparator.join(myDict)
4 print(x)
12. format():
string.format(value1, value2...)
value1, value2... :
Required. One or more values that should be formatted
and inserted in the string.
The values are either a list of values separated by c
ommas, a key=value list, or a combination of both.
The values can be of any data type.
The format() method formats the specified value(s) and insert them inside the string's
placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in
the Placeholder section below.
The format() method returns the formatted string.
In [43]: 1 # The placeholders can be identified using named indexes {price}, numbere
2 txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
3 txt2 = "My name is {0}, I'm {1}".format("John",36)
4 txt3 = "My name is {}, I'm {}".format("John",36)
5
6 print(txt1)
7 print(txt2)
8 print(txt3)
13. lower():
The lower() method returns a string where all characters are lower case.
hello my friends
14. upper():
The upper() method returns a string where all characters are in upper case.
HELLO MY FRIENDS
15. rjust():
string.rjust(length, character)
The rjust() method will right align the string, using a specified character (space is default)
as the fill character.
Python 6
Python 20
%%%%%%%%%%%%%%Python 20
16. ljust():
string.ljust(length, character)
The ljust() method will left align the string, using a specified character (space is default) as
the fill character.
Python 6
Python 20
Python%%%%%%%%%%%%%% 20
17. center():
string.center(length, character)
The center() method will center align the string, using a specified character (space is
default) as the fill character.
Python 6
Python 20
%%%%%%%Python%%%%%%% 20
18. rstrip():
string.rstrip(characters)
The rstrip() method removes any trailing characters (characters at the end a string), space
is the default trailing character to remove.
python
,,,,,ssaaww
banana
19. lstrip():
string.lstrip(characters)
The lstrip() method removes any leading characters (space is the default leading character
to remove)
In [55]: 1 txt = " python "
2 print(txt.lstrip())
python
ww.....banana
banana
20. strip():
string.strip(characters)
banana
banana
gg.....banana
21. replace():
string.replace(oldvalue, newvalue, count)
It returns a copy of the string in which the occurrences of old have been replaced with
new, optionally restricting the number of replacements to max.
All occurrences of the specified phrase will be replaced, if nothing else is specified.
I like Gaming
three three was a race horse, two two was three too.
three three was a race horse, two two was one too.
In [68]: 1 #If given sub-string not found then it will provide old string as output
2 s = "I like coding"
3 print(s.replace('C',"Gaming"))
I like coding
22. split():
string.split(separator, maxsplit)
separator : Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator
maxsplit : Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences"
['apple', 'banana#cherry#orange']
23. rsplit():
string.rsplit(separator, maxsplit)
separator : Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator
maxsplit : Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences"
The rsplit() method splits a string into a list, starting from the right.
If no "max" is specified, this method will return the same as the split() method.
Note: When maxsplit is specified, the list will contain the specified number of elements
plus one.
24. splitlines():
string.splitlines(keeplinebreaks)
keeplinebreaks : Optional. Specifies if the line breaks should be included (True), or not (False).
Default value is False
The splitlines() method splits a string into a list. The splitting is done at line breaks.
25. title():
The title() method returns a string where the first character in every word is upper case.
Like a header, or a title.
If the word contains a number or a symbol, the first letter after that will be converted to
upper case.
In [88]: 1 # Make the first letter in each word upper case:
2 txt = "Welcome to my 2nd world"
3 print(txt.title())
Note that the first letter after a non-alphabet letter is converted into a upper case letter:
26. zfill():
string.zfill(len)
The zfill() method adds zeros (0) at the beginning of the string, until it reaches the
specified length.
If the value of the len parameter is less than the length of the string, no filling is done.
27. swapcase():
The swapcase() method returns a string where all the upper case letters are lower case
and vice versa.
28. isalnum():
The isalnum() method returns True if all the characters are alphanumeric, meaning
alphabet letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.
In [93]: 1 txt = "Python3"
2 print(txt.isalnum())
True
False
False
29. isalpha():
The isalpha() method returns True if all the characters are alphabet letters (a-z).
Example of characters that are not alphabet letters: (space)!#%&? etc.
True
False
30. isascii():
The isascii() method returns True if all the characters are ascii characters (a-z).
True
In [102]: 1 txt = "అమ్మ "
2 x = txt.isascii()
3 print(x)
False
False
Reference:https://www.w3schools.com/charsets/ref_html_ascii.asp
(https://www.w3schools.com/charsets/ref_html_ascii.asp)
ENQ 5 enquiry
ACK 6 acknowledge
BS 8 backspace
HT 9 horizontal tab
LF 10 line feed
VT 11 vertical tab
FF 12 form feed
CR 13 carriage return
SO 14 shift out
SI 15 shift in
Char Number Description
SYN 22 synchronize
CAN 24 cancel
EM 25 end of medium
SUB 26 substitute
ESC 27 escape
FS 28 file separator
GS 29 group separator
RS 30 record separator
US 31 unit separator
32 space
! 33 exclamation mark
# 35 number sign
$ 36 dollar sign
% 37 percent sign
& 38 ampersand
' 39 apostrophe
( 40 left parenthesis
) 41 right parenthesis
* 42 asterisk
+ 43 plus sign
, 44 comma
- 45 hyphen
. 46 period
/ 47 slash
0 48 digit 0
1 49 digit 1
2 50 digit 2
3 51 digit 3
Char Number Description
4 52 digit 4
5 53 digit 5
6 54 digit 6
7 55 digit 7
8 56 digit 8
9 57 digit 9
: 58 colon
; 59 semicolon
< 60 less-than
= 61 equals-to
> 62 greater-than
? 63 question mark
@ 64 at sign
A 65 uppercase A
B 66 uppercase B
C 67 uppercase C
D 68 uppercase D
E 69 uppercase E
F 70 uppercase F
G 71 uppercase G
H 72 uppercase H
I 73 uppercase I
J 74 uppercase J
K 75 uppercase K
L 76 uppercase L
M 77 uppercase M
N 78 uppercase N
O 79 uppercase O
P 80 uppercase P
Q 81 uppercase Q
R 82 uppercase R
S 83 uppercase S
T 84 uppercase T
U 85 uppercase U
V 86 uppercase V
W 87 uppercase W
Char Number Description
X 88 uppercase X
Y 89 uppercase Y
Z 90 uppercase Z
\ 92 backslash
^ 94 caret
_ 95 underscore
` 96 grave accent
a 97 lowercase a
b 98 lowercase b
c 99 lowercase c
d 100 lowercase d
e 101 lowercase e
f 102 lowercase f
g 103 lowercase g
h 104 lowercase h
i 105 lowercase i
j 106 lowercase j
k 107 lowercase k
l 108 lowercase l
m 109 lowercase m
n 110 lowercase n
o 111 lowercase o
p 112 lowercase p
q 113 lowercase q
r 114 lowercase r
s 115 lowercase s
t 116 lowercase t
u 117 lowercase u
v 118 lowercase v
w 119 lowercase w
x 120 lowercase x
y 121 lowercase y
z 122 lowercase z
31. isdecimal():
The isdecimal() method returns True if all the characters are decimals (0-9).
This method can also be used on unicode objects. See example below.
True
True
False
False
32. isdigit():
The isdigit() method returns True if all the characters are digits, otherwise False.
Exponents, like ², are also considered to be a digit.
In [115]: 1 s="PYTHON"
2 print(s.isdigit())
False
In [116]: 1 s="12345"
2 print(s.isdigit())
True
False
In [118]: 1 s="25 is my age"
2 print(s.isdigit())
False
33. isidentifier():
The isidentifier() method returns True if the string is a valid identifier, otherwise False.
A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-
9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.
True
False
In [121]: 1 a = "MyFolder"
2 b = "Demo002"
3 c = "2bring"
4 d = "my demo"
5
6 print(a.isidentifier())
7 print(b.isidentifier())
8 print(c.isidentifier())
9 print(d.isidentifier())
True
True
False
False
34. islower():
Return true if all charcters are in string is lower case,otherwise False.
In [123]: 1 s = "PYTHON"
2 print(s.islower())
False
In [124]: 1 s = "Python"
2 print(s.islower())
False
In [125]: 1 s = "python"
2 print(s.islower())
True
In [126]: 1 s = "python123"
2 print(s.islower())
True
True
In [128]: 1 s = "python@"
2 print(s.islower())
True
35. isupper():
Return true if all charcters are in string is upper case,otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
In [129]: 1 s = "PYTHON"
2 print(s.isupper())
True
In [130]: 1 s = "pYTHON"
2 print(s.isupper())
False
In [131]: 1 s = "PYTHON123"
2 print(s.isupper())
True
In [132]: 1 s = "PYTHON123%"
2 print(s.isupper())
True
36. isspace():
The isspace() method returns True if all the characters in a string are whitespaces,
otherwise False.
True
False
True
False
In [137]: 1 PyStr="\t\t"
2 print(PyStr.isspace())
3 PyStr="\n"
4 print(PyStr.isspace())
True
True
37. isprintable():
The isprintable() method returns True if all the characters are printable, otherwise False.
Example of none printable character can be carriage return and line feed.
In [138]: 1 txt = "Hello! Are you #1?"
2 x = txt.isprintable()
3 print(x)
True
False
False
38. isnumeric():
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise
False.
Exponents, like ² and ¾ are also considered to be numeric values.
"-1" and "1.5" are NOT considered numeric values, because all the characters in the string
must be numeric, and the - and the . are not.
True
True
True
False
False
False
39. istitle():
The istitle() method returns True if all words in a text start with a upper case letter, AND
the rest of the word are lower case letters, otherwise False.
Symbols and numbers are ignored.
True
False
True
True
True
40. maketrans():
str.maketrans(x, y, z)
x :
Required. If only one parameter is specified, this has to be a dictio
nary describing how to perform the replace. If two or more parameters
are specified, this parameter has to be a string specifying the chara
cters you want to replace.<br>
y :
Optional. A string with the same length as parameter x. Each characte
r in the first parameter will be replaced with the corresponding char
acter in this string.<br>
z :
Optional. A string describing which characters to remove from the ori
ginal string.
The maketrans() method returns a mapping table that can be used with the translate()
method to replace specified characters.
In [159]: 1 #Create a mapping table, and use it in the translate() method to replace
2
3 txt = "Hello Sam!"
4 mytable = txt.maketrans("S", "P")
5 print(txt.translate(mytable))
Hello Pam!
Hi Joe!
Hi eoJ!
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [162], in <cell line: 4>()
2 x = "Sma"
3 y = "eJo0"
----> 4 mytable = txt.maketrans(x, y)
5 print(txt.translate(mytable))
ValueError: the first two maketrans arguments must have equal length
In [164]: 1 #The third parameter in the mapping table describes characters that you w
2
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 mytable = txt.maketrans(x, y, z)
8 print(txt.translate(mytable))
G i Joe!
G i Joe!
In [166]: 1 #The maketrans() method itself returns a dictionary describing each repla
2
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 print(txt.maketrans(x, y, z))
{109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104:
None, 116: None}
41. translate():
string.translate(table)
table : Required. Either a dictionary, or a mapping table describing how to perform the replace
The translate() method returns a string where some specified characters are replaced with
the character described in a dictionary, or in a mapping table.
Use the maketrans() method to create a mapping table.
If a character is not specified in the dictionary/table, the character will not be replaced.
If you use a dictionary, you must use ascii codes instead of characters.
In [170]: 1 #use a dictionary with ascii codes to replace 83 (S) with 80 (P):
2 mydict = {83: 80}
3 txt = "Hello Sam!"
4 print(txt.translate(mydict))
Hello Pam!
In [175]: 1 print(chr(83))
2 print(chr(80))
S
P
Hello Pam!
Hi Joe!
In [183]: 1 #The third parameter in the mapping table describes characters that you w
2
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 mytable = txt.maketrans(x, y, z)
8 print(txt.translate(mytable))
G i Joe!
{109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104:
None, 116: None}
In [181]: 1 #The same example as above, but using a dictionary instead of a mapping t
2
3 txt = "Good night Sam!"
4 mydict = {109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103
5 print(txt.translate(mydict))
G i Joe!
42. partition():
string.partition(value)
The partition() method searches for a specified string, and splits the string into a tuple
containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
Note: This method searches for the first occurrence of the specified string.
In [188]: 1 # Search for the word "bananas", and return a tuple with three elements:
2 # 1 - everything before the "match"
3 # 2 - the "match"
4 # 3 - everything after the "match"
5
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.partition("bananas")
8 print(x)
('I could eat ', 'bananas', ' all day, bananas are my favorite fruit')
In [190]: 1 # If the specified value is not found, the partition() method returns a t
2 # 1 - the whole string
3 # 2 - an empty string
4 # 3 - an empty string:
5
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.partition("apples")
8 print(x)
('I could eat bananas all day, bananas are my favorite fruit', '', '')
43. rpartition():
string.rpartition(value)
The rpartition() method searches for the last occurrence of a specified string, and splits the
string into a tuple containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
In [189]: 1 # Search for the last occurrence of the word "bananas", and return a tupl
2
3 # 1 - everything before the "match"
4 # 2 - the "match"
5 # 3 - everything after the "match"
6
7 txt = "I could eat bananas all day, bananas are my favorite fruit"
8 x = txt.rpartition("bananas")
9 print(x)
('I could eat bananas all day, ', 'bananas', ' are my favorite fruit')
In [191]: 1 # If the specified value is not found, the rpartition() method returns a
2 # 1 - an empty string
3 # 2 - an empty string
4 # 3 - the whole string:
5
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.rpartition("apples")
8 print(x)
('', '', 'I could eat bananas all day, bananas are my favorite fruit')
Booleans
Booleans represent one of two values: True or False.
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the
Boolean answer:
True
False
False
In [195]: 1 print(bool("Hello"))
2 print(bool(15))
True
True
In [196]: 1 x = "Hello"
2 y = 15
3
4 print(bool(x))
5 print(bool(y))
True
True
In fact, there are not many values that evaluate to False, except empty values, such as (), [], {},
"", the number 0, and the value None.
In [198]: 1 # True values
2 print(bool("abc"))
3 print(bool(123))
4 print(bool(["apple", "cherry", "banana"]))
True
True
True
False
False
False
False
False
False
False
True
In [204]: 1 #Example : Print "YES!" if the function returns True, otherwise print "NO
2
3 def myFunction() :
4 return True
5
6 if myFunction():
7 print("YES!")
8 else:
9 print("NO!")
YES!
Python also has many built-in functions that return a boolean value, like the isinstance()
function, which can be used to determine if an object is of a certain data type:
True