Strings in Python
What is a String? A string in Python is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).
Strings are immutable, meaning once created, you can’t change their contents directly — you can only create new strings.
Creating Strings
Python
# Single quotes name = 'Ashish' # Double quotes language = "Python" # Triple quotes (used for multi-line text) message = '''Hello, Welcome to Python!'''
✅ All of these are valid strings.
String Example:
Python
# Example of string usage greeting = "Hello, World!" print(greeting) # Output: Hello, World! print(type(greeting)) # Output: <class 'str'>
What is Indexing in String? Indexing means accessing individual characters in a string by their position number (called index).
• Python assigns index numbers to each character in a string.
• These indexes can be positive (from start) or negative (from end).
1. Positive Indexing (Left to Right) Indexing starts from 0 for the first character.
Python
text = "Python" print(text[0]) # P → First character print(text[1]) # y → Second character print(text[5]) # n → Sixth (last) character
If we try to access an index that doesn’t exist →
Python
print(text[6]) # ❌ IndexError: string index out of range
2. Negative Indexing (Right to Left) Negative indexing starts from -1 for the last character, moving backward.
Python
text = "Python" print(text[-1]) # n → Last character print(text[-2]) # o → Second last print(text[-6]) # P → First character (same as text[0])
If we go beyond negative range:
Python
print(text[-7]) # ❌ IndexError
Bonus Tip – Access Both Directions Dynamically If we want to access the same position from both directions:
Example:
Python
text = "Python" i = 2 print(text[i]) # Positive indexing print(text[-(len(text)-i)]) # Negative equivalent