In Python, a string is a sequence of characters enclosed in quotes. Strings are a versatile and commonly used data type.
Creating Strings
Strings can be created using:
- Single Quotes (‘):
single_quote = 'Hello'
- Double Quotes (“):
double_quote = "World"
- Triple Quotes (”’ or “””):
Used for multi-line strings. Also serves as docstrings for documentation.
multi_line = '''This is a multi-line string.'''
Accessing Strings
Strings are indexed and immutable. You can access individual characters or substrings using:
- Indexing: Access individual characters using positive or negative indices.
s = "Python" print(s[0]) # Output: 'P' (first character) print(s[-1]) # Output: 'n' (last character)
- Slicing: Extract substrings using [start:end:step].
s = "Python" print(s[0:3]) # Output: 'Pyt' (characters from index 0 to 2) print(s[:3]) # Output: 'Pyt' (start defaults to 0) print(s[3:]) # Output: 'hon' (end defaults to length) print(s[::2]) # Output: 'Pto' (every 2nd character)
String Operations
Operation | Description | Example | Output |
Concatenation | Combine strings | Hello’ + ‘ World’ | Hello World’ |
Repetition | Repeat a string | Hi’ * 3 | HiHiHi’ |
Length | Get string length | len(‘Hello’) | 5 |
Membership | Check substring existence | P’ in ‘Python’ | TRUE |
Common String Methods
- Changing Case:
s = "Python" print(s.lower()) # Output: 'python' print(s.upper()) # Output: 'PYTHON' print(s.capitalize()) # Output: 'Python' print(s.title()) # Output: 'Python' print(s.swapcase()) # Output: 'pYTHON'
- Trimming Whitespace:
s = " Hello World " print(s.strip()) # Output: 'Hello World' print(s.lstrip()) # Output: 'Hello World ' print(s.rstrip()) # Output: ' Hello World'
- Finding and Replacing:
s = "Hello World" print(s.find('World')) # Output: 6 (start index of 'World') print(s.replace('World', 'Python')) # Output: 'Hello Python'
- Splitting and Joining:
s = "apple,banana,cherry" print(s.split(',')) # Output: ['apple', 'banana', 'cherry'] fruits = ['apple', 'banana', 'cherry'] print(','.join(fruits)) # Output: 'apple,banana,cherry'
- Checking Content:
s = "Python3" print(s.isalpha()) # Output: False (contains a digit) print(s.isdigit()) # Output: False print(s.isalnum()) # Output: True (letters and digits only) print(s.islower()) # Output: False print(s.isupper()) # Output: False
String Formatting
- f-strings (Recommended, Python 3.6+):
name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.") # Output: My name is Alice and I am 30 years old.
- str.format():
print("My name is {} and I am {} years old.".format(name, age)) # Output: My name is Alice and I am 30 years old.
- % Formatting:
print("My name is %s and I am %d years old." % (name, age)) # Output: My name is Alice and I am 30 years old.
Escape Sequences
Special characters in strings can be represented using escape sequences:
Escape Sequence
|
Description | Example | Output |
\’ | Single quote | It\’s nice’ | It’s nice’ |
\” | Double quote | “\”Hello\”” | “Hello”‘ |
\\ | Backslash | “C:\\path” | C:\path’ |
\n | Newline | “Hello\nWorld” | Multi-line |
\t | Tab | “Hello\tWorld” | Hello World’ |
Raw Strings
- Use r or R before a string to ignore escape sequences:
path = r"C:\new_folder\file.txt" print(path) # Output: C:\new_folder\file.txt
Immutability
- Strings are immutable, meaning their contents cannot be changed. Operations like concatenation or slicing create a new string.
s = "Hello" s[0] = "J" # Error: 'str' object does not support item assignment s = "Jello" # Reassigning creates a new string