String Indexing and Slicing in Python

String Indexing and Slicing in Python

In Python, strings are sequences of characters that can be accessed using indexing and slicing operations. Here’s a comprehensive explanation with examples:

Indexing

Strings in Python are zero-indexed, meaning the first character has index 0.

python

text = "Python"

Index positions:

text

P y t h o n
0 1 2 3 4 5

Positive Indexing (left to right)

python

print(text[0])   # 'P' - first character
print(text[1])   # 'y' - second character
print(text[5])   # 'n' - last character

Negative Indexing (right to left)

Negative indices count from the end of the string:

text

P  y  t  h  o  n
-6 -5 -4 -3 -2 -1

python

print(text[-1])  # 'n' - last character
print(text[-2])  # 'o' - second last character
print(text[-6])  # 'P' - first character

Slicing

Slicing allows you to extract a substring using the syntax: string[start:stop:step]

Basic Slicing

python

text = "Python Programming"

# Get characters from index 0 to 5 (not including 5)
print(text[0:5])   # 'Pytho'

# Get characters from index 7 to end
print(text[7:])     # 'Programming'

# Get characters from beginning to index 5
print(text[:5])     # 'Pytho'

# Get the entire string
print(text[:])      # 'Python Programming'

# Get every second character
print(text[::2])    # 'Pto rgamn'

Negative Slicing

python

# Get last 5 characters
print(text[-5:])    # 'mming'

# Get all characters except last 5
print(text[:-5])    # 'Python Progr'

# Get characters from -10 to -5
print(text[-10:-5]) # ' Progr'

Step Parameter

python

# Reverse the string
print(text[::-1])   # 'gnimmargorP nohtyP'

# Get every 3rd character
print(text[::3])    # 'Ph rn'

Practical Examples

  1. Extracting file extensions:

python

filename = "document.pdf"
extension = filename[-3:]
print(extension)  # 'pdf'
  1. Getting domain from email:

python

email = "user@example.com"
domain = email[email.index('@')+1:]
print(domain)  # 'example.com'
  1. Checking if a string is a palindrome:

python

word = "madam"
is_palindrome = word == word[::-1]
print(is_palindrome)  # True
  1. Extracting parts of a date:

python

date = "2023-04-15"
year = date[:4]
month = date[5:7]
day = date[8:]
print(year, month, day)  # '2023' '04' '15'

Remember that strings are immutable in Python, 

1. Basic String Operations

Concatenation (+)

python

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # "Hello World"

Repetition (*)

python

word = "Hi"
repeated = word * 3
print(repeated)  # "HiHiHi"

Length (len())

python

text = "Python"
print(len(text))  # 6

in and not in Operators in Python Strings

The in and not in operators are membership operators used to check if a substring exists within a string. They return boolean values (True or False).

in Operator

Checks if a substring exists in a string.

Syntax:

python

substring in string

Examples:

python

text = "Python programming is fun"

# Check for single character
print('P' in text)        # True
print('z' in text)        # False

# Check for multiple characters
print('pro' in text)      # True
print('gram' in text)     # True
print('java' in text)     # False

# Case-sensitive check
print('python' in text)   # False (because of case difference)

not in Operator

Checks if a substring does not exist in a string.

Syntax:

python

substring not in string

Examples:

python

text = "Python programming is fun"

print('java' not in text)     # True
print('fun' not in text)      # False
print('Fun' not in text)      # True (case-sensitive)

Practical Use Cases

  1. Input validation:

python

email = input("Enter your email: ")
if "@" not in email or "." not in email:
    print("Invalid email address")
  1. Search functionality:

python

products = ["Python book", "Java course", "JavaScript tutorial"]
search_term = "python"
results = [p for p in products if search_term.lower() in p.lower()]
print(results)  # ['Python book']
  1. Conditional execution:

python

filename = "report.pdf"
if ".pdf" in filename:
    print("This is a PDF file")
  1. Security check:

python

user_input = input("Enter comment: ")
if "script" not in user_input.lower():
    print("Comment accepted")
else:
    print("Potential XSS attack detected")

Important Notes

  1. These operations are case-sensitive:

python

print('python' in 'Python')  # False
  1. They work with empty strings:

python

print('' in 'Python')       # True (empty string is always considered present)
print('' not in 'Python')   # False
  1. Performance: These operations are highly optimized in Python and execute very quickly even for large strings.
  2. For exact matching rather than substring checking, use == instead:

python

print('python' == 'Python')  # False

Similar Posts

  • Closure Functions in Python

    Closure Functions in Python A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope. Simple Example python def outer_function(x): # This is the enclosing scope def inner_function(y): # inner_function can access ‘x’ from outer_function’s scope return x + y return inner_function…

  • install Python, idle, Install pycharm

    Step 1: Download Python Step 2: Install Python Windows macOS Linux (Debian/Ubuntu) Open Terminal and run: bash Copy Download sudo apt update && sudo apt install python3 python3-pip For Fedora/CentOS: bash Copy Download sudo dnf install python3 python3-pip Step 3: Verify Installation Open Command Prompt (Windows) or Terminal (macOS/Linux) and run: bash Copy Download python3 –version # Should show…

  • Method overriding

    Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class). When a method is called on an object of the child class, the child’s version of the method is…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • pop(), remove(), clear(), and del 

    pop(), remove(), clear(), and del with 5 examples each, including slicing where applicable: 1. pop([index]) Removes and returns the item at the given index. If no index is given, it removes the last item. Examples: 2. remove(x) Removes the first occurrence of the specified value x. Raises ValueError if not found. Examples: 3. clear() Removes all elements from the list, making it empty. Examples: 4. del Statement Deletes elements by index or slice (not a method, but a…

Leave a Reply

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