Python Strings
String Fundamentals
Strings in Python are sequences of Unicode characters used to represent text.
Key characteristics:
- Immutable (cannot be changed after creation)
- Defined with single (' '), double (" "), or triple quotes (''' ''' or """ """)
- Support indexing and slicing
- Provide many built-in methods for manipulation
Example
# String creation examples
greeting = 'Hello World!'
multi_line = """This is a
multi-line
string"""
# String operations
print(len(greeting)) # 12
print(greeting[0]) # 'H'
Output
12 H
String Indexing
ℹ️ Note: Python strings use zero-based indexing.
Index | Character | Description |
---|---|---|
0 | 'H' | First character |
-1 | '!' | Last character |
6 | 'W' | Seventh character |
1:5 | 'ello' | Slice from index 1 to 4 |
String Immutability
Strings are immutable. Any method that appears to change a string actually returns a new one.
⚠️ Warning: Trying to assign to a character index (e.g., str[0] = 'X') raises a TypeError.
Example
original = "Python"
modified = original.replace("P", "J")
print(original) # "Python"
print(modified) # "Jython"
Output
Python Jython
Common String Methods
ℹ️ Note: These methods create new strings without modifying the original.
Method | Description | Example |
---|---|---|
upper() | Convert to uppercase | "hello".upper() → 'HELLO' |
lower() | Convert to lowercase | "HELLO".lower() → 'hello' |
strip() | Remove whitespace from both ends | " hi ".strip() → 'hi' |
split() | Split into list by delimiter | "a,b,c".split(',') → ['a','b','c'] |
join() | Join iterable with separator | '-'.join(['a','b']) → 'a-b' |
find() | Return index of substring (or -1) | "hello".find('e') → 1 |
startswith() | Check if string starts with value | "python".startswith('py') → True |
endswith() | Check if string ends with value | "notes.txt".endswith('.txt') → True |