0% found this document useful (0 votes)
9 views

python chapter no 2 notes

Uploaded by

Komal Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

python chapter no 2 notes

Uploaded by

Komal Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter 2

1.Precedence and Associativity of Operators in Python


In Python, operators have different levels of precedence, which determine the order in which
they are evaluated. When multiple operators are present in an expression, the ones with higher
precedence are evaluated first. In the case of operators with the same precedence, their
associativity comes into play, determining the order of evaluation. Associativity determines the
sequence of operations when two operators share the same priority.
The direction in which any given expression with more than one operator having the same
precedence is assessed is called as associativity.
Almost every operator is associative from left to right.

Operator Precedence and Associativity in Python


Please see the following precedence and associativity table for reference. This table lists all
operators from the highest precedence to the lowest precedence.

Precedence Operators Description Associativity


1 ( ) Parentheses Left to right
2 x[index], x[index:index] Subscription, slicing Left to right
3 await x Await expression N/A
4 ** Exponentiation Right to left
5 +x, -x, ~x Positive, negative, bitwise NOT Right to left
Multiplication, matrix, division, floor
6 *, @, /, //, % Left to right
division, remainder
7 +, – Addition and subtraction Left to right
8 <<, >> Shifts Left to right
9 & Bitwise AND Left to right
10 ^ Bitwise XOR Left to right
11 | Bitwise OR Left to right
in, not in, is, is not, <, <=, >, Comparisons, membership tests,
12 Left to Right
>=, !=, == identity tests
13 not x Boolean NOT Right to left
Precedence Operators Description Associativity
14 and Boolean AND Left to right
15 or Boolean OR Left to right
16 if-else Conditional expression Right to left
17 lambda Lambda expression N/A
18 := Assignment expression (walrus

2. Python Type Conversion


In programming, type conversion is the process of converting data of one type to another. For
example: converting int data to str.

There are two types of type conversion in Python.

 Implicit Conversion - automatic type conversion


 Explicit Conversion - manual type conversion

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another. This is known as
implicit type conversion.

integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))

output

Value: 124.23
Data Type: <class 'float'>

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type
of the objects.

num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))

Output

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

3. Conditional statements in python


Python If-else statements
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Statement Description

The if statement is used to test a specific condition. If the condition is true, a block of code
If Statement
(if-block) will be executed.

If - else The if-else statement is similar to if statement except the fact that, it also provides the
Statement block of the code for the false case of the condition to be checked. If the condition
provided in the if statement is false, then the else statement will be executed.

Nested if
The elif statement
Statement
Nested if statements enable us to use if - else statement inside an outer if statement.

Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.

Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.

The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.

The syntax of the if-statement is given below.


1. if expression:
2. statement

Example 1

1. # Simple Python program to understand the if statement


2. num = int(input("enter the number:"))
3. # Here, we are taking an integer num and taking input dynamically
4. if num%2 == 0:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("The Given number is an even number")

Output:

enter the number: 10


The Given number is an even number

Example 2 : Program to print the largest of the three numbers.

1. # Simple Python Program to print the largest of the three numbers.


2. a = int (input("Enter a: "));
3. b = int (input("Enter b: "));
4. c = int (input("Enter c: "));
5. if a>b and a>c:
6. # Here, we are checking the condition. If the condition is true, we will enter the block
7. print ("From the above three numbers given a is largest");
8. if b>a and b>c:
9. # Here, we are checking the condition. If the condition is true, we will enter the block
10. print ("From the above three numbers given b is largest");
11. if c>a and c>b:
12. # Here, we are checking the condition. If the condition is true, we will enter the block
13. print ("From the above three numbers given c is largest");

Output:

Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in
the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
The syntax of the if-else statement is given below.

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.

1. # Simple Python Program to check whether a person is eligible to vote or not.


2. age = int (input("Enter your age: "))
3. # Here, we are taking an integer num and taking input dynamically
4. if age>=18:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("You are eligible to vote !!");
7. else:
8. print("Sorry! you have to wait !!");

Output:

Enter your age: 90


You are eligible to vote !!
Example 2: Program to check whether a number is even or not.

1. # Simple Python Program to check whether a number is even or not.


2. num = int(input("enter the number:"))
3. # Here, we are taking an integer num and taking input dynamically
4. if num%2 == 0:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("The Given number is an even number")
7. else:
8. print("The Given Number is an odd number")

Output:

enter the number: 10


The Given number is even number

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.

The syntax of the elif statement is given below.

1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1

1. # Simple Python program to understand elif statement


2. number = int(input("Enter the number?"))
3. # Here, we are taking an integer number and taking input dynamically
4. if number==10:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("The given number is equals to 10")
7. elif number==50:
8. # Here, we are checking the condition. If the condition is true, we will enter the block
9. print("The given number is equal to 50");
10. elif number==100:
11. # Here, we are checking the condition. If the condition is true, we will enter the block
12. print("The given number is equal to 100");
13. else:
14. print("The given number is not equal to 10, 50 or 100");

Output:

Enter the number?15


The given number is not equal to 10, 50 or 100
4.Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices
for running the loops. The basic functionality of all the techniques is the same, although the
syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.

Loop Type & Description


Name of
Sr.No.
the loop

Repeats a statement or group of statements while a given condition is


1 While loop
TRUE. It tests the condition before executing the loop body.

This type of loop executes a code block multiple times and abbreviates
2 For loop
the code that manages the loop variable.

3 Nested loops We can iterate a loop inside another loop.

1.While Loop
While loops are used in Python to iterate until a specified condition is met. However, the
statement in the program that follows the while loop is executed once the condition changes to
false.

Syntax of the while loop is:

1. while <condition>:
2. { code block }

All the coding statements that follow a structural command define a code block. These
statements are intended with the same number of spaces. Python groups statements together with
indentation.
Code

1. # Python program to show how to use a while loop


2. counter = 0
3. # Initiating the loop
4. while counter < 10: # giving the condition
5. counter = counter + 3
6. print("Python Loops")

Output:
Python Loops
Python Loops
Python Loops
Python Loops

Using else Statement with while Loops

As discussed earlier in the for loop section, we can use the else statement with the while loop
also. It has the same syntax.

Code

1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed
9. else:
10. print("Code block inside the else statement")

Output:

Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement

Single statement while Block

The loop can be declared in a single statement, as seen below. This is similar to the if-else block,
where we can write the code block in a single line.

Code

1. # Python program to show how to write a single statement while loop


2. counter = 0
3. while (count < 3): print("Python Loops")

2.The for Loop


Python's for loop is designed to repeatedly execute a code block while iterating through a list,
tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is
known as iteration.
Syntax of the for Loop

1. for value in sequence:


2. { code block }

In this case, the variable value is used to hold the value of every item present in the sequence
before the iteration begins until this particular iteration is completed.

Loop iterates until the final item of the sequence are reached.

Code

1. # Python program to show how the for loop works


2.
3. # Creating a sequence which is a tuple of numbers
4. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
5.
6. # variable to store the square of the number
7. square = 0
8.
9. # Creating an empty list
10. squares = []
11.
12. # Creating a for loop
13. for value in numbers:
14. square = value ** 2
15. squares.append(square)
16. print("The list of squares is", squares)

Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

Using else Statement with for Loop

As already said, a for loop executes the code block until the sequence element is reached. The
statement is written right after the for loop is executed after the execution of the for loop is
complete.

Only if the execution is complete does the else statement comes into play. It won't be executed if
we exit the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

1. # Python program to show how if-else statements work


2.
3. string = "Python Loop"
4.
5. # Initiating a loop
6. for s in a string:
7. # giving a condition in if block
8. if s == "o":
9. print("If block")
10. # if condition is not satisfied then else block will be executed
11. else:
12. print(s)

Output:

P
y
t
h
If block
n

L
If block
If block
p

Now similarly, using else with for loop.

Syntax:

1. for value in sequence:


2. # executes the statements until sequences are exhausted
3. else:
4. # executes these statements when for loop is completed

Code

1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")
Output:

3
9
3
9
7
These are the odd numbers present in the tuple

The range() Function

With the help of the range() function, we may produce a series of numbers. range(10) will
produce values between 0 and 9. (10 numbers).

We can give specific start, stop, and step size values in the manner range(start, stop, step size). If
the step size is not specified, it defaults to 1.

Since it doesn't create every value it "contains" after we construct it, the range object can be
characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is not an
iterator.

The example that follows will make this clear.

Code

1. # Python program to show the working of range() function


2.
3. print(range(15))
4.
5. print(list(range(15)))
6.
7. print(list(range(4, 9)))
8.
9. print(list(range(5, 25, 4)))

Output:

range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]

To iterate through a sequence of items, we can apply the range() method in for loops. We can use
indexing to iterate through the given sequence by combining it with an iterable's len() function.
Here's an illustration.

Code

1. # Python program to iterate over a sequence with the help of indexing


2.
3. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
4.
5. # iterating over tuple_ using range() function
6. for iterator in range(len(tuple_)):
7. print(tuple_[iterator].upper())

Output:

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

5.Loop Control Statements


Now we will discuss the loop control statements in detail. We will see an example of each
control statement.

Continue Statement

It returns the control to the beginning of the loop.

Code

1. # Python program to show how the continue statement works


2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == "o" or string == "p" or string == "t":
6. continue
7. print('Current Letter:', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s

Break Statement

It stops the execution of the loop when the break statement is reached.

Code
1. # Python program to show how the break statement works
2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == 'L':
6. break
7. print('Current Letter: ', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Pass Statement

Pass statements are used to create empty loops. Pass statement is also employed for classes,
functions, and empty control statements.

Code

1. # Python program to show how the pass statement works


2. for a string in "Python Loops":
3. pass
4. print( 'Last Letter:', string)

Output:

Last Letter: s

5.

6. Strings in python
Python String
Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes. The computer does not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that Python strings
are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Consider the following example in Python to create a string.

Syntax:

1. str = "Hi Python !"

Here, if we check the type of the variable str using a Python script

1. print(type(str)), then it will print a string (str).

In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string of
length 1.

Creating String in Python


We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string or
docstrings.

1. #Using single quotes


2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)

Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring

Strings indexing and splitting


Like other languages, the indexing of the Python strings starts from 0. For example, The string
"HELLO" is indexed as given in the below figure.
Consider the following example:

1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])

Output:

H
E
L
L
O
IndexError: string index out of range

As shown in Python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in Python to access the substring from the given
string. Consider the following example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if
str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.

Consider the following example:

1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])

Output:
JAVATPOINT
AVAT
VA
JAV
TPO

We can do the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1. The second rightmost index indicates -2, and so on. Consider the following
image.

Consider the following example

1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])

Output:

T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range

Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object
doesn't support item assignment i.e., A string can only be replaced with new string since its
content cannot be partially replaced. Strings are immutable in Python.

Consider the following example.

Example 1

1. str = "HELLO"
2. str[0] = "h"
3. print(str)

Output:

Traceback (most recent call last):


File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment

However, in example 1, the string str can be assigned completely to a new content as specified
in the following example.
Example 2

1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)

Output:

HELLO
hello

Deleting the String


As we know that strings are immutable. We cannot delete or remove the characters from the
string. But we can delete the entire string using the del keyword.

1. str = "JAVATPOINT"
2. del str[1]
Output:

TypeError: 'str' object doesn't support item deletion

Now we are deleting entire string.

1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)

Output:

NameError: name 'str1' is not defined

String Operators
Operator Description

+ It is known as concatenation operator used to join the strings given either side of the operator.

* It is known as repetition operator. It concatenates the multiple copies of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the specified range.

It is known as membership operator. It returns if a particular sub-string is present in the


in
specified string.

It is also a membership operator and does the exact reverse of in. It returns true if a particular
not in
substring is not present in the specified string.

It is used to specify the raw string. Raw strings are used in the cases where we need to print the
r/R actual meaning of escape characters such as "C://python". To define any string as a raw string,
the character r or R is followed by the string.

It is used to perform string formatting. It makes use of the format specifiers used in C
% programming like %d or %f to map their values in python. We will discuss how formatting is
done in python.

Example

Consider the following example to understand the real use of Python operators.

1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

Python String Formatting


Escape Sequence

Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given
statement can be written in single quotes or double quotes but it will raise the SyntaxError as it
contains both single and double-quotes.

Example
Consider the following example to understand the real use of Python operators.

1. str = "They said, "Hello what's going on?""


2. print(str)

Output:

SyntaxError: invalid syntax

We can use the triple quotes to accomplish this problem but Python provides the escape
sequence.

The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a
special character and it interpreted differently. The single quotes inside the string must be
escaped. We can apply the same as in the double quotes.
Example -

1. # using triple quotes


2. print('''''They said, "What's there?"''')
3.
4. # escaping single quotes
5. print('They said, "What\'s going on?"')
6.
7. # escaping double quotes
8. print("They said, \"What's going on?\"")

Output:

They said, "What's there?"


They said, "What's going on?"
They said, "What's going on?"

The list of an escape sequence is given below:

Sr. Escape Sequence Description Example

print("Python1 \
Python2 \
1. \newline It ignores the new line. Python3")
Output:

Python1 Python2 Python3


print("\\")
2. \\ Backslash Output:

\
print('\'')
3. \' Single Quotes Output:

'
print("\"")
4. \\'' Double Quotes Output:

"
5. \a ASCII Bell
print("\a")

print("Hello \b World")
6. \b ASCII Backspace(BS) Output:

Hello World
7. \f ASCII Formfeed print("Hello \f World!")
Hello World!
print("Hello \n World!")
8. \n ASCII Linefeed
Output:
Hello
World!
print("Hello \r World!")
9. \r ASCII Carriege Return(CR) Output:

World!
print("Hello \t World!")
10. \t ASCII Horizontal Tab Output:

Hello World!
print("Hello \v World!")
11. \v ASCII Vertical Tab Output:

Hello
World!
print("\110\145\154\154\157")
12. \ooo Character with octal value
Output:
Hello
print("\x48\x65\x6c\x6c\x6f")
13 \xHH Character with hex value. Output:

Hello

Here is the simple example of escape sequence.

1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")

Output:

C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation

We can ignore the escape sequence from the given string by using the raw string. We can do this
by writing r or R in front of the string. Consider the following example.

1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")

Output:
C:\\Users\\DEVANSH SHARMA\\Python32

The format() method


The format() method is the most flexible and useful method in formatting strings. The curly
braces {} are used as the placeholder in the string and replaced by the format() method
argument. Let's have a look at the given an example:

1. # Using Curly braces


2. print("{} and {} both are the best friend".format("Devansh","Abhishek"))
3.
4. #Positional Argument
5. print("{1} and {0} best players ".format("Virat","Rohit"))
6.
7. #Keyword Argument
8. print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

Output:

Devansh and Abhishek both are the best friend


Rohit and Virat best players
James,Peter,Ricky

Python String Formatting Using % Operator


Python allows us to use the format specifiers used in C's printf statement. The format specifiers
in Python are treated in the same way as they are treated in C. However, Python provides an
additional operator %, which is used as an interface between the format specifiers and their
values. In other words, we can say that it binds the format specifiers to the values.

Consider the following example.

1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My
value is %s"%(Integer,Float,String))

Output:

Hi I am Integer ... My value is 10


Hi I am float ... My value is 1.290000
Hi I am string ... My value is Devansh

Python String functions


Python provides various in-built functions that are used for string handling. Many String fun

Method Description
It capitalizes the first character of the String. This function is
capitalize()
deprecated in python3

casefold() It returns a version of s suitable for case-less comparisons.

It returns a space padded string with the original string centred with
center(width ,fillchar)
equal number of left and right spaces.

It counts the number of occurrences of a substring in a String


count(string,begin,end)
between begin and end index.

decode(encoding = 'UTF8', errors =


Decodes the string using codec registered for encoding.
'strict')

Encode S using the codec registered for encoding. Default encoding


encode()
is 'utf-8'.

endswith(suffix It returns a Boolean value if the string terminates with given suffix
,begin=0,end=len(string)) between begin and end.

It defines tabs in string to multiple spaces. The default space value is


expandtabs(tabsize = 8)
8.

find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.

format(value) It returns a formatted version of S, using the passed value.

index(subsring, beginIndex, It throws an exception if string is not found. It works same as find()
endIndex) method.

It returns true if the characters in the string are alphanumeric i.e.,


isalnum() alphabets or numbers and there is at least 1 character. Otherwise, it
returns false.

It returns true if all the characters are alphabets and there is at least
isalpha()
one character, otherwise False.

isdecimal() It returns true if all the characters of the string are decimals.

It returns true if all the characters are digits and there is at least one
isdigit()
character, otherwise False.

isidentifier() It returns true if the string is the valid identifier.


It returns true if the characters of a string are in lower case,
islower()
otherwise false.

isnumeric() It returns true if the string contains only numeric characters.

It returns true if all the characters of s are printable or s is empty,


isprintable()
false otherwise.

It returns false if characters of a string are in Upper case, otherwise


isupper()
False.

It returns true if the characters of a string are white-space, otherwise


isspace()
false.

It returns true if the string is titled properly and false otherwise. A


istitle() title string is the one in which the first character is upper-case
whereas the other characters are lower-case.

It returns true if all the characters of the string(if exists) is true


isupper()
otherwise it returns false.

join(seq) It merges the strings representation of the given sequence.

len(string) It returns the length of a string.

It returns the space padded strings with the original string left
ljust(width[,fillchar])
justified to the given width.

lower() It converts all the characters of a string to Lower case.

It removes all leading whitespaces of a string and can also be used to


lstrip()
remove particular character from leading.

It searches for the separator sep in S, and returns the part before it,
partition() the separator itself, and the part after it. If the separator is not found,
return S and two empty strings.

maketrans() It returns a translation table to be used in translate function.

It replaces the old sequence of characters with the new sequence.


replace(old,new[,count])
The max characters are replaced if max is given.

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in backward direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in backward direction.


Returns a space padded string having original string right justified to
rjust(width,[,fillchar])
the number of characters specified.

It removes all trailing whitespace of a string and can also be used to


rstrip()
remove particular character from trailing.

It is same as split() but it processes the string from the backward


rsplit(sep=None, maxsplit = -1) direction. It returns the list of words in the string. If Separator is not
specified then the string splits according to the white-space.

Splits the string according to the delimiter str. The string splits
split(str,num=string.count(str)) according to the space if the delimiter is not provided. It returns the
list of substring concatenated with the delimiter.

splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.

It returns a Boolean value if the string starts with given str between
startswith(str,beg=0,end=len(str))
begin and end.

strip([chars]) It is used to perform lstrip() and rstrip() on the string.

swapcase() It inverts case of all characters in a string.

It is used to convert the string into the title-case i.e., The string
title()
meEruT will be converted to Meerut.

It translates the string according to the translation table passed in the


translate(table,deletechars = '')
function .

upper() It converts all the characters of a string to Upper Case.

Returns original string leftpadded with zeros to a total of width


zfill(width) characters; intended for numbers, zfill() retains any sign given (less
one zero).

You might also like