Python

In Python, a String is a sequence of characters used to store and manipulate text. Strings are one of the most common data types and are considered immutable, meaning once a string is created, you cannot change its individual characters.

1. Theoretical Overview

String Creation

Strings in Python are versatile. You can create them using:

  • Single Quotes (' '): Most common for short strings.

  • Double Quotes (" "): Useful if the string itself contains a single quote (e.g., "It's Python").

  • Triple Quotes (''' ''' or """ """): Used for Multi-line strings or docstrings. They preserve the exact formatting, including new lines.

Understanding Indexing

Every character in a string is assigned a numerical address called an Index.

  • Positive Indexing: Starts from 0 (left to right). The first character is 0, the second is 1, etc.

  • Negative Indexing: Starts from -1 (right to left). This is perfect for accessing the end of a string without knowing its exact length.

The Immutability Rule

If you try to execute my_string[0] = "A", Python will throw a TypeError. To "change" a string, you must create a new one using methods or slicing.

2. Code Implementation

A. Creating Strings

Python
# Single and Double Quotes
simple_str = 'Hello'
better_str = "Python is 'Great'"

# Multi-line String
multi_line = """This string 
spans across 
multiple lines."""

print(simple_str)
print(multi_line)

B. Accessing Characters (Indexing)

Python
sample = "PROGRAM"

# Positive Indexing
print(sample[0])    # Output: P
print(sample[3])    # Output: G

# Negative Indexing
print(sample[-1])   # Output: M (Last character)
print(sample[-3])   # Output: R (Third from last)

3. Operations & Properties

OperationCode ExampleResult
Lengthlen("Hi")2
Concatenation"Py" + "thon""Python"
Repetition"Go" * 3"GoGoGo"
Membership"P" in "Python"True

4. Common Errors to Avoid

  • IndexError: Happens when you try to access an index that doesn't exist (e.g., index 10 for a 5-character string).

  • Case Sensitivity: "Python" and "python" are different strings because indexing is based on ASCII/Unicode values.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now