1. String Basics
A string is a sequence of characters enclosed in single (') or double (") quotes.
Common Operations
text = "Python"
text + " Basics" # Concatenate strings
text * 3 # Repeat a string
len(text) # String length
2. Escape Sequences
Escape sequences represent special characters inside strings.
| Escape | Description |
|---|---|
\n |
New line |
\t |
Horizontal tab |
\\ |
Backslash (\) |
\' |
Single quote |
\" |
Double quote |
\r |
Carriage return |
\f |
Form feed |
\a |
Bell (alert) |
\b |
Backspace |
\0 |
Null character |
Example:
print("Hello\nWorld")
3. String Slicing
Extract part of a string using indexes.
Syntax
string[start:end]
-
startis inclusive. -
endis exclusive.
Example:
text = "Python"
text[0:2] # "Py"
text[:4] # "Pyth"
text[2:] # "thon"
text[-1] # "n"
4. String Formatting
% Formatting (Legacy)
"%s" % "Python"
"%d" % 10
"%.2f" % 3.14159
Common format specifiers:
| Code | Description |
|---|---|
%s |
String |
%c |
Character |
%d |
Integer |
%f |
Float |
%o |
Octal |
%x |
Hexadecimal |
%% |
Percent sign |
str.format()
"Hello, {}".format("Python")
"{0} {1}".format("Hello", "World")
"{name}".format(name="Python")
Alignment:
"{:<10}".format("Hi") # Left
"{:>10}".format("Hi") # Right
"{:^10}".format("Hi") # Center
"{:*^10}".format("Hi") # Fill with *
Floating-point precision:
"{:.2f}".format(3.14159)
Escape braces:
"{{Python}}"
f-Strings (Recommended)
Available in Python 3.6+.
name = "Python"
version = 3.13
f"{name} {version}"
f"{version:.1f}"
f"{name:>10}"
Supports:
- Variables
- Expressions
- Dictionary access
- Alignment
- Number formatting
Example:
x = 10
y = 20
f"{x} + {y} = {x + y}"
5. Common String Methods
Search
text.count("a")
text.find("a")
text.index("a")
-
count(): Count occurrences. -
find(): Return index, or-1if not found. -
index(): Return index, or raiseValueError.
Case Conversion
text.upper()
text.lower()
Remove Whitespace
text.strip()
text.lstrip()
text.rstrip()
Replace
text.replace("Python", "Java")
Split
text.split()
text.split(",")
Returns a list of substrings.
Join
",".join(["A", "B", "C"])
Output:
A,B,C
Notes
- Strings are immutable, meaning their contents cannot be changed directly.
- Most string methods return a new string instead of modifying the original.
Note: AI was used to assist in the drafting and formatting of this post.
Top comments (0)