Python Unit 2
Python Unit 2
and Operators
Python Strings
• A string is a sequence of characters. 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 the manipulated characters in the combination of the 0’s and
1’s. Each character is encoded in the ASCII or Unicode character set.
So we can say that Python strings are also called the collection of
Unicode characters.
• Strings in Python are sequences of characters (Unicode
characters).
• Syntax:
• str = "Python programming language"
• If we check the type of the variable str using a python code:
• print(type(str))
Strings are objects of Python’s built-in class str.
String literals are written by enclosing a sequence of characters
in single quotes ('Python'), double quotes ("Python") or triple quotes
('''Python''' or """Python""").
• str1 = 'python'
• print(str1)
• str2 = "python"
• print(str2)
• str3 = """python"""
• print(str3)
• Output:
• python
• python
• python
• Single Quotes:
• str1 = 'This is Python string'
• print(str1)
• Double Quotes:
• str1 = "Another string"
• print(str1)
•
• triple quotes:
• str1 = "Another string"
• print(str1)
• Multi-line Strings:
• str1 = '''this is a
• multiline string
• created with triple quotes.'''
• print(str1)
Understanding Indexing in Python
Strings
• Python treats strings as arrays of characters, where each
character has an index.
• Positive Indexing (Left to Right): Starts from 0 and goes up to
length-1.
• Negative Indexing (Right to Left): Starts from -1 (last
character) and goes backward
•
String as character array
• Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string. Strings in Python
are arrays of bytes representing Unicode characters.
• str = "HELLO“
• str[0] = 'H'
• str[1] = 'E'
• str[2] = 'L'
• str[3] = 'L'
• str[4] = 'O‘
• Example: get the character at a position 1(remember that the first character has the
position 0) a=HELLO
• Print(a(1)
• o/p: E
String slicing
• 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.
• str = "HELLO“
• str[0] = 'H'
• str[1] = 'E'
• str[2] = 'L'
• str[3] = 'L'
• str[4] = 'O'
Slicing Examples:
• str[0:] = 'HELLO'
• str[:5] = 'HELLO'
• str[:3] = 'HEL'
• str[0:2] = 'HE'
• str[1:4] = 'ELL'
• 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.
-
Negative Indexing
• Use negative indexes to start the slice from the end of the string. It starts
from the rightmost character, which is indicated as -1. The second
rightmost index indicates -2, and so on.
String Methods
• center() – Center-aligning a string
• This method returns a centered string of the specified width, padded with a
specified character (default is space).
• The center() method aligns a string in the center of a specified width.
• It also allows filling extra spaces with a specified character (default is space).
• string.center(width, fill_char)
• width: Total width of the output string
• fill_char: Character used to fill the empty spaces (default is space). If
we want to use symbol we can write in “”. Like”+”,”#”,”@”,”_” etc.
• Eg:1 =>str1 = "Python is fun!"
• Str2=print(str1.center(25, "-"))
• # Output: "------Python is fun!-----“
• Eg-2=> text = "Python"
• centered_text = text.center(10, '*')
• print(centered_text)
• # Output: '**Python**‘=> so here we count python length is 6 and we
give 10 so give 2 space before and 2 space after string. So total length
is 10.
2. count(substring, start, end)
• The count() method in Python is used to count the occurrences of a
specified substring within a given string.
• Syntax: string.count(substring, start, end)
• substring: The text you want to count within the string.
• start (optional): The starting index from where to begin counting.
• end (optional): The ending index where the search stops.
• eg 1=>text = "hello world, hello Python"
• count_hello = text.count("hello")
• print(count_hello) # Output: 2
3. join(iterable)
• The .join() method in Python is used to concatenate the elements of an iterable (like a list or
tuple) into a single string, with a specified separator.
• fruits = ["Apple", "Banana", "Cherry"] #list
• colors = ("Red", "Green", "Blue") #tuple
• syntax: separator.join(iterable)
• separator: The string used to separate each element in the iterable. (e.g., space " ",
comma ",“,”@”,”_”,”$”,”#” etc.).
• iterable: A list, tuple, or other iterable containing string elements.
• words = ["Hello", "Python", "World"]
• text = " ".join(words)
• print(text) # Output: 'Hello Python World‘
• if we put separator as a # so output like => Hello#Python#World
.
.
4. len(string)
• Returns the length (number of characters) in a string.
• The len() function is used to return the length of an object, such as a
string, list, tuple, or dictionary.
• Finding the length of a string (number of characters).
✔ Counting elements in a list, tuple, or dictionary.
✔ Useful for loops and conditionals (e.g., checking if a list is empty).
• Syntax: len(iterable)
• text = "Python"
• print(len(text)) # Output: 6
Explanation:
•The string "Python" contains 6 characters (P, y, t, h, o, n).
•The len() function counts the number of characters and
returns 6
• fruits = ["Apple", "Banana", "Cherry"]
•print(len(fruits)) # Output: 3
• The list contains 3 elements, so len() returns 3
max(string)
• Returns the highest alphabetical character in a string.
• text = "apple"
• print(max(text)) # Output: 'p' (since 'p' has the highest ASCII value)
How It Works?
1.The function evaluates each character based on its ASCII value.
2.ASCII values of characters in "apple":
• 'a' → 97
•'p' → 112
•'p' → 112
•'l' → 108
•'e' → 101
3.The highest ASCII value is 112 (which corresponds to 'p').
4.Hence, max(text) returns 'p'.
• numbers = [3, 9, 1, 5]
• print(max(numbers)) # Output: 9
min(string)
• Returns the lowest alphabetical character in a string.
• text = "apple"
• print(min(text)) # Output: 'a‘
split(separator, maxsplit)
• Splits the string into a list using the specified separator.
• string.split(separator, maxsplit)
• separator (optional): The character(s) where the split occurs. Default is
whitespace.
•maxsplit (optional): The maximum number of splits. Default is unlimited
• text = "apple,banana,grape"
• print(text.split(",")) # Output: ['apple', 'banana', 'grape']
Operators in Python
• Python provides different types of operators to perform operations on
variables and values. Below is a detailed explanation with examples.
• Arithmetic Operators
•
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division (returns float)
% Modulus (returns remainder)
** Exponentiation (power)
// Floor Division (integer division)
Example:
• a = 10
• b=3
• print(a + b) # Output: 13
• print(a - b) # Output: 7
• print(a * b) # Output: 30
• print(a / b) # Output: 3.3333
• print(a % b) # Output: 1
• print(a ** b) # Output: 1000 (10^3)
• print(a // b) # Output: 3 (Integer division)
Assignment Operators
• These operators assign values to variables.
Operator Example Equivalent to
+= a += 3 a=a+3
-= a -= 3 a=a-3
*= a *= 3 a=a*3
**= A**=3 a=a^3
/= a /= 3 a=a/3
//= a //= 3 a = a // 3
Example
• a = 10
• a += 5 # Same as a = a + 5
• print(a) # Output: 15
• a //= 3 # Same as a = a // 3
• print(a) # Output: 5
# Example of Arithmetic Operators
in Python
• a = 10
• b=3
• # Addition
• print("Addition (a + b):", a + b) # 10 + 3 = 13
• # Subtraction
• print("Subtraction (a - b):", a - b) # 10 - 3 = 7
• # Multiplication
• print("Multiplication (a * b):", a * b) # 10 * 3 = 30
• # Division
• print("Division (a / b):", a / b) # 10 / 3 = 3.3333
• # Floor Division
• print("Floor Division (a // b):", a // b) # 10 // 3 = 3 (removes decimal part)
• # Modulus (Remainder)
• print("Modulus (a % b):", a % b) # 10 % 3 = 1 (remainder when 10 is divided by 3)
• # Exponentiation (Power)
• print("Exponentiation (a ** b):", a ** b) # 10 ** 3 = 1000 (10 raised to the power of 3)
output
• Addition (a + b): 13
• Subtraction (a - b): 7
• Multiplication (a * b): 30
• Division (a / b): 3.3333333333333335
• Floor Division (a // b): 3
• Modulus (a % b): 1
• Exponentiation (a ** b): 1000
# Example of Assignment Operators in Python
• # Example of Assignment Operators in Python
Comparison Operators
• A comparison operator in Python is used to compare two values. These
operators return a Boolean value (True or False) based on the comparison
result. They are mainly used in decision-making statements like if, while, and
loops.
• Other Names for Comparison Operators:
• Relational Operators
• Conditional Operators
• Both names refer to the same set of operators used for value comparison.
# Example of Comparison Operators in Python
• a = 10
• b=5
• # Greater than
• print("a > b:", a > b) # True
• # Less than
• print("a < b:", a < b) # False
• # Equal to
• print("a == b:", a == b) # False
• # Not equal to
• print("a != b:", a != b) # True
• # Greater than or equal to
• print("a >= b:", a >= b) # True
• # Less than or equal to
• print("a <= b:", a <= b) # False
• Output:
• a > b: True
• a < b: False
• a == b: False
• a != b: True
• a >= b: True
• a <= b: False
Logical Operators in Python
Logical operators in Python are used to combine multiple conditions
(Boolean expressions) and return a True or False result. There are three main
logical operators: and, or, and not.
# Example of Logical Operators in
Python
• a = True
• b = False
• # AND Operator Example
• print("a and b:", a and b) # False (Both must be True)
• # OR Operator Example
• print("a or b:", a or b) # True (At least one must be True)
• # NOT Operator Example
• print("not a:", not a) # False (Reverses the value)
• print("not b:", not b) # True (Reverses the value)
Output:
and b: False
a or b: True
not a: False
not b: True
Identity and Membership Operators
in Python
• Python has two types of special operators:
• Identity Operators (is, is not) → Used to compare memory locations
of objects.
• Membership Operators (in, not in) → Used to check if a value exists
in a sequence (like list, tuple, or string).
• Identity Operators (is, is not)
•
• # Identity Operators Example
• a = [1, 2, 3] # List
• b=a # Assigning the same list to b
• c = [1, 2, 3] # A new list with the same values
• print(a is b) # True (Same memory location)
• print(a is c) # False (Different objects)
• print(a is not c) # True (Different memory location)
• Explanation:
• b = a → b refers to the same object as a, so a is b is True.
• c = [1, 2, 3] → Even though c has the same values as a, it is a different object, so a is c
is False.
Membership Operators (in, not
in)
•
Example for Membership Operators