UNIT-2: Python Strings and Operators

Python Strings

  • A string in Python is a sequence of characters enclosed in single (‘ ‘), double (” “), or triple quotes (”’ ”’ or “”” “””).
  • Strings are immutable, meaning they cannot be changed after creation.
  • Python provides various ways to manipulate and work with strings efficiently.

Multiline String, String as Character Array, Triple Quotes

1. Multiline Strings

Python allows storing multiple lines in a string using triple quotes (''' or """).
Example:
multi_line = """This is a multi-line string in Python.""" print(multi_line)

OUTPUT :-

This is a multi-line string in Python.

2. String as a Character Array.

In Python, strings are sequences of characters and can be accessed like an array (list) using indexing.
Example:
text = "Python"
print(text[0])   # Output: P (First character)
print(text[3])   # Output: h
Strings are immutable: You cannot modify a string after creation, but you can reassign it
text[0] = "J"  # ❌ Error: Strings are immutable

3. Triple Quotes (''' or """).

Triple quotes (''' or """) are used for multiline strings and docstrings (function documentation).
Example:
def sample_function():
    """This function demonstrates docstrings in Python."""
    return "Hello"

print(sample_function.__doc__)  # Output: This function demonstrates docstrings in Python.
Use Cases:
  • Multiline strings
  • Function documentation (docstrings)

Slicing Strings, Negative Indexing, String Length, Concatenation

1. Slicing Strings

String slicing extracts a substring using [start:end:step] notation.

Syntax:

substring = string[start:end]  # End index is exclusive
				

EXAMPLE

text = "Python Programming"
print(text[0:6])   # Output: Python
print(text[7:18])  # Output: Programming
print(text[:6])    # Output: Python (Start from 0)
print(text[7:])    # Output: Programming (Till end)
print(text[::2])   # Output: Pto rgamn (Every second character)

2. Negative Indexing

Python allows negative indexing to access characters from the end.
text = "Python"
print(text[-1])   # Output: n (Last character)
print(text[-3:])  # Output: hon (Last three characters)
print(text[:-2])  # Output: Pyth (Excludes last two characters)
Benefits:
  • Easy access to the last characters without knowing string length.

3. Finding String Length

The len() function returns the number of characters in a string.
text = "Hello, Python!"
print(len(text))  # Output: 14

4. String Concatenation

Concatenation joins two or more strings using the + operator.

Example:

text1 = "Hello"
text2 = "World"
result = text1 + " " + text2  # Adding space between words
print(result)  # Output: Hello World

Alternative: Using join() method

words = ["Hello", "World"]
result = " ".join(words)
print(result)  # Output: Hello World

String Methods.

Method Description Example
center(width) Centers the string within a given width "Python".center(10) → ' Python '
count(substring) Counts occurrences of a substring "banana".count("a") → 3
join(iterable) Joins elements of an iterable with a separator "-".join(["A", "B", "C"]) → "A-B-C"
len(string) Returns the length of a string len("Python") → 6
max(string) Returns the highest character (ASCII-wise) max("hello") → 'o'
min(string) Returns the lowest character (ASCII-wise) min("hello") → 'e'
replace(old, new) Replaces occurrences of a substring "hello".replace("l", "x") → "hexxo"
lower() Converts to lowercase "Python".lower() → "python"
upper() Converts to uppercase "python".upper() → "PYTHON"
split(separator) Splits a string into a list "hello world".split(" ") → ['hello', 'world']

Examples of String Methods

1. center() Method

text = "Python"
print(text.center(10))  # Output: '  Python  '

2. count() Method

text = "banana"
print(text.count("a"))  # Output: 3

    

3. join() Method

words = ["Python", "is", "fun"]
result = " ".join(words)
print(result)  # Output: Python is fun

4. replace() Method

 
text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text)  # Output: Hello Python

5. upper() and lower() Methods

text = "Python"
print(text.upper())  # Output: PYTHON
print(text.lower())  # Output: python

6. split() Method.

text = "apple,banana,cherry"
words = text.split(",")
print(words)  # Output: ['apple', 'banana', 'cherry']

Operators in Python.

  • Operators in Python are symbols that perform operations on variables and values.
  • Python supports different types of operators, such as arithmetic, assignment, comparison, logical, identity, and membership operators.

Arithmetic Operators.

Arithmetic operators perform mathematical operations like addition, subtraction, multiplication, division, etc..
Operator Description Example
+ Addition 5 + 3 → 8
- Subtraction 10 - 4 → 6
* Multiplication 6 * 2 → 12
/ Division (returns float) 9 / 2 → 4.5
// Floor Division (rounds down) 9 // 2 → 4
% Modulus (remainder) 9 % 2 → 1
** Exponentiation (power) 2 ** 3 → 8
a = 10 b = 3 print(a + b) # 13 print(a - b) # 7 print(a * b) # 30 print(a / b) # 3.3333 print(a % b) # 1 print(a ** b) # 1000 (10^3) print(a // b) # 3 (Rounded down)

Assignment Operators

Assignment operators are used to assign values to variables.
Operator Example Equivalent To
= a = 5 Assigns 5 to a
+= a += 3 a = a + 3
-= a -= 2 a = a - 2
*= a *= 4 a = a * 4
/= a /= 2 a= a / 2
//= a //= 2 a = a // 2
%= a %= 3 a = a % 3
**= a **= 2 a = a ** 2
x = 10 x += 5 # x = x + 5 print(x) # Output: 15 x *= 2 # x = x * 2 print(x) # Output: 30 x //= 3 # x = x // 3 print(x) # Output: 10

Comparison Operators.

Comparison operators compare two values and return True or False.
Operator Description Example
== Equal to 5 == 5 → True
!= Not equal to 5 != 3 → True
> Greater than 10 > 3 → True
< Less than 2 < 5 → True
>= Greater than or equal to 10 >= 10 → True
<= Less than or equal to 5 <= 6 → True
a = 10 b = 20 print(a == b) # False print(a != b) # True print(a > b) # False print(a < b) # True print(a >= 10) # True print(b <= 10) # False

Logical Operators.

Logical operators are used to combine conditional statements.
Operator Description Example
and Returns True if both conditions are True (5 > 3 and 10 > 5) → True
or Returns True if at least one condition is True (5 > 3 or 10 < 5) → True
not Reverses the condition not(5 > 3) → False
x = 5
y = 10

print(x > 2 and y > 5)   # True (Both conditions are True)
print(x > 10 or y > 5)   # True (One condition is True)
print(not (x > 2))       # False (Reverses the condition)

Identity and Membership Operators.

1. Identity Operators (is, is not)

Identity operators check if two variables refer to the same memory location.
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a is c)  # True (Same memory location)
print(a is b)  # False (Different memory location)
print(a is not b)  # True
    

2. Membership Operators (in, not in)

Membership operators check if a value exists in a sequence (list, tuple, string, dictionary).
Operator Description Example
is Returns True if two variables refer to the same object a is b
is not Returns True if two variables refer to different objects a is not b
Operator Description Example
in Returns True if a value is in a sequence "a" in "apple" → True
not in Returns True if a value is not in a sequence "z" not in "apple" → True
text = "Python Programming"
print("Python" in text)     # True
print("Java" in text)       # False
print("Java" not in text)   # True

Conclusion.

  • Python strings are sequences of characters that support slicing, indexing, and modification using built-in methods.
  • Multiline strings use triple quotes.
  • Slicing and negative indexing help extract substrings easily.
  • String methods like replace(), join(), and split() make string operations more efficient.
  • Arithmetic operators perform mathematical operations.
  • Assignment operators update variable values.
  • Comparison operators compare values and return True/False.
  • Logical operators combine conditions.
  • Identity operators check object identity in memory.
  • Membership operators check if an element is in a sequence.

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.