Python Strings and String Functions
What is a String in Python?
A string is a sequence of characters enclosed in single (' '), double (" "), or triple quotes (''' ''' or """ """).
Characteristics of Strings
- Immutable: Cannot be changed after creation
- Indexed: Supports indexing
- Slicable: Can extract substrings using slicing
Common String Methods
capitalize() - Converts first character to uppercase
casefold() - Converts string to lowercase (stronger than lower)
center(width) - Centers string in a field of given width
count(sub) - Counts occurrences of substring
encode() - Encodes string to bytes
endswith(suffix) - Checks if string ends with the suffix
expandtabs(n) - Sets tab size to n
find(sub) - Returns index of first occurrence of substring
format() - Formats strings using placeholders
index(sub) - Same as find() but raises error if not found
isalnum() - True if all characters are alphanumeric
isalpha() - True if all characters are letters
isdigit() - True if all characters are digits
islower() - True if all letters are lowercase
isupper() - True if all letters are uppercase
isspace() - True if string contains only whitespaces
istitle() - True if string is in title case
join(iterable) - Joins elements of iterable with string
len() - Returns length of string
lower() - Converts to lowercase
upper() - Converts to uppercase
lstrip() - Removes leading spaces
rstrip() - Removes trailing spaces
strip() - Removes spaces from both ends
replace(old, new) - Replaces old substring with new
rfind() - Finds last occurrence of substring
rindex() - Same as rfind() but raises error if not found
split() - Splits string into list
rsplit() - Splits string from the right
splitlines() - Splits string at line breaks
startswith(prefix) - Checks if string starts with prefix
swapcase() - Swaps letter case
title() - Converts first letter of each word to uppercase
zfill(width) - Pads string with zeros on the left