In Python, a string is a sequence of characters enclosed within single quotes ('), double quotes ("), or triple quotes (''' or """). Strings are immutable, meaning once created, their content cannot be changed. They are one of the most commonly used data types for representing text.
Strings can be created directly by assigning a sequence of characters to a variable. Basic operations include concatenation (+), repetition (*), and membership testing (in).
Strings support indexing (accessing individual characters) and slicing (accessing substrings). Indexing starts at 0, and negative indices count from the end.
Python provides numerous built-in methods for string manipulation:
| Method | Description | Example |
|---|---|---|
str.upper() |
Converts to uppercase | "hello".upper() → "HELLO" |
str.lower() |
Converts to lowercase | "HELLO".lower() → "hello" |
str.strip() |
Removes leading/trailing whitespace | " hi ".strip() → "hi" |
str.split(sep) |
Splits string into list by separator | "a,b,c".split(",") → ['a','b','c'] |
str.join(iterable) |
Joins iterable elements with string | ",".join(['a','b']) → "a,b" |
str.replace(old, new) |
Replaces occurrences of substring | "hello".replace('l','x') → "hexxo" |
str.find(sub) |
Returns index of first occurrence | "hello".find('e') → 1 |
str.startswith(prefix) |
Checks if string starts with prefix | "hello".startswith('he') → True |
str.endswith(suffix) |
Checks if string ends with suffix | "hello".endswith('lo') → True |
str.isalpha() |
Checks if all characters are alphabetic | "abc".isalpha() → True |
str.isdigit() |
Checks if all characters are digits | "123".isdigit() → True |
str.isalnum() |
Checks if alphanumeric | "a1b2".isalnum() → True |
Python offers multiple ways to format strings: