UNIT-3: Python Strings and Operators
UNIT-3: Python Strings and Operators
3.1 Python Strings.
A string in Python is a sequence of characters enclosed within single (
'), double ("), or triple (''' """) quotes. Strings are immutable, meaning they cannot be changed once created.
3.1.1 Multiline String, String as Character Array, Triple Quotes
Multiline Strings
Python allows multi-line strings using triple quotes (''' """).
Example:
multi_line = """This is a multiline string in Python. It spans multiple lines.""" print(multi_line)
String as a Character Array
Strings are arrays of characters, allowing us to access individual characters using indexing.
Example:
text = "Python" print(text[0]) # Output: P print(text[2]) # Output: t
Triple Quotes (''' """)
Triple quotes allow multi-line strings and are also used for docstrings.
Example:
info = '''Python is a powerful language. It is widely used in AI and web development.''' print(info)
3.1.2 Slicing Strings, Negative Indexing, String Length, Concatenation
Slicing Strings
Python allows extracting a part of a string using slicing.
Syntax:
string[start:end] # Extracts substring from index 'start' to 'end-1'
Example .
text = "Python Programming" print(text[0:6]) # Output: Python print(text[:6]) # Output: Python (start index is 0 by default) print(text[7:]) # Output: Programming (till end)
Negative Indexing
Negative indexing allows counting from the end of the string.
Example:
text = "Python" print(text[-1]) # Output: n (last character) print(text[-3:]) # Output: hon (last 3 characters) print(text[:-3]) # Output: Pyt (everything except last 3)
Finding String Length
The len() function returns the length of a string.
Example:
text = "Python Programming" print(len(text)) # Output: 18
String Concatenation
Strings can be joined using the + operator.
Example:
str1 = "Hello" str2 = "World" result = str1 + " " + str2 # Adding space manually print(result) # Output: Hello World
3.1.3 String Methods
Python provides several built-in string methods for string manipulation.
1. center() → Centers the string with padding
text = "Python" print(text.center(20, "-")) # Output: '-------Python-------'
2. count() → Counts occurrences of a substring
text = "banana" print(text.count("a")) # Output: 3
3. join() → Joins elements of an iterable into a string.
words = ["Hello", "Python", "World"] print("-".join(words)) # Output: Hello-Python-World
4. len() → Returns the length of a string
text = "Python" print(len(text)) # Output: 6
5. max() & min() → Returns the max/min character based on ASCII values
text = "apple" print(max(text)) # Output: 'p' (highest ASCII value) print(min(text)) # Output: 'a' (lowest ASCII value)
6. replace() → Replaces occurrences of a substring
text = "Hello World" print(text.replace("World", "Python")) # Output: Hello Python
7. lower() & upper() → Converts string to lowercase/uppercase
text = "Python" print(text.lower()) # Output: python print(text.upper()) # Output: PYTHON
8. split() → Splits a string into a list based on a delimiter
text = "apple,banana,cherry" print(text.split(",")) # Output: ['apple', 'banana', 'cherry']
Summary Table of String Methods
3.2 Operators in Python.
Operators in Python are symbols used to perform operations on variables and values. Python provides several types of operators.
3.2.1 Arithmetic Operators
Arithmetic operators perform mathematical calculations.
| Operator | Description | Example | Output |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 10 - 4 | 6 |
| * | Multiplication | 6 * 2 | 12 |
| / | Division | 9 / 2 | 4.5 |
| // | Floor Division | 9 // 2 | 4 |
| % | Modulus (Remainder) | 9 % 2 | 1 |
| ** | Exponentiation (Power) | 2 ** 3 | 8 |
a = 10 b = 3 print(a + b) # Addition: 13 print(a - b) # Subtraction: 7 print(a * b) # Multiplication: 30 print(a / b) # Division: 3.333... print(a % b) # Modulus: 1 print(a ** b) # Exponentiation: 1000 (10^3) print(a // b) # Floor Division: 3
3.2.2 Assignment Operators
Assignment operators are used to assign values to variables.
| Operator | Description | Example | Equivalent To |
|---|---|---|---|
| = | Assign value | a = 10 | a = 10 |
| += | Add and assign | a += 5 | a = a + 5 |
| -= | Subtract and assign | a -= 3 | a = a - 3 |
| *= | Multiply and assign | a *= 2 | a = a * 2 |
| /= | Divide and assign | a /= 4 | a = a / 4 |
| //= | Floor divide and assign | a //= 2 | a = a // 2 |
x = 10 x += 5 # x = x + 5 print(x) # Output: 15 x -= 3 # x = x - 3 print(x) # Output: 12 x *= 2 # x = x * 2 print(x) # Output: 24 x /= 4 # x = x / 4 print(x) # Output: 6.0
3.2.3 Comparison Operators.
Comparison operators compare values and return a Boolean (
TrueorFalse).
| Operator | Description | Example | Output |
|---|---|---|---|
| == | Equal to | 5 == 5 | True |
| != | Not equal to | 5 != 3 | True |
| > | Greater than | 10 > 3 | True |
| < | Less than | 2 < 8 | True |
| >= | Greater than or equal to | 7 >= 7 | True |
| <= | Less than or equal to | 5 <= 6 | True |
a = 10 b = 5 print(a == b) # False print(a != b) # True print(a > b) # True print(a < b) # False print(a >= 10) # True print(b <= 5) # True
3.2.4 Logical Operators
Logical operators are used to combine multiple conditions.
| Operator | Description | Example | Output |
|---|---|---|---|
| and | Returns True if both conditions are True | (5 > 2) and (3 < 6) | True |
| or | Returns True if at least one condition is True | (5 < 2) or (3 < 6) | True |
| not | Reverses the result (True → False, False → True) | not(5 == 5) | False |
a = 5 b = 10 c = 15 print(a < b and b < c) # True (both conditions are True) print(a > b or b < c) # True (one condition is True) print(not(a == 5)) # False (negates True)
3.2.5 Identity and Membership Operators
Identity Operators (is, is not)
Identity operators compare memory locations of objects (not just values).
| Operator | Description | Example | Output |
|---|---|---|---|
| is | Returns True if both variables refer to the same object | x is y | True if same object |
| is not | Returns True if variables refer to different objects | x is not y | True if different objects |
x = [1, 2, 3] y = x # y points to the same object as x z = [1, 2, 3] # z is a new object with same content print(x is y) # True (same memory reference) print(x is z) # False (different objects) print(x is not z) # True
Membership Operators (in, not in)
Membership operators check if a value exists in a sequence (like a list or string).
| Operator | Description | Example | Output |
|---|---|---|---|
| in | Returns True if value exists in a sequence | 'a' in 'apple' | True |
| not in | Returns True if value does not exist in a sequence | 'z' not in 'apple' | True |