Python Strings Complete Guide
Learn all Python string operations - creation, manipulation, built-in methods, slicing, formatting with practical examples and complete reference.
String Methods
40+ built-in
Slicing
Substring extraction
Formatting
f-strings, format()
Search/Replace
find(), replace()
What are Python Strings?
Strings in Python are sequences of characters enclosed in quotes. They are immutable, meaning once created, they cannot be changed. Python provides rich functionality for string manipulation through built-in methods and operations.
Key Concept
Python strings are immutable - any operation that modifies a string creates a new string. Strings support indexing (str[0]), slicing (str[1:5]), and various built-in methods.
# Creating strings
single_quote = 'Hello World'
double_quote = "Python Programming"
triple_quote = '''Multi-line
string example'''
triple_double = """Another multi-line
string example"""
# String operations
str1 = "Hello"
str2 = "Python"
concatenation = str1 + " " + str2 # "Hello Python"
repetition = str1 * 3 # "HelloHelloHello"
length = len(str1) # 5
# String indexing
text = "Python"
first_char = text[0] # 'P'
last_char = text[-1] # 'n'
third_char = text[2] # 't'
# String slicing
substring = text[1:4] # 'yth'
substring2 = text[:3] # 'Pyt'
substring3 = text[3:] # 'hon'
substring4 = text[::2] # 'Pto' (every 2nd character)
reversed_str = text[::-1] # 'nohtyP' (reverse string)
Python String Methods Complete Reference
Python provides over 40 built-in string methods for various operations. Here's a comprehensive table of all string methods with examples.
Complete String Methods Reference Table
| Category | Method | Description | Syntax Example | Result |
|---|---|---|---|---|
| Case Conversion | upper() | Converts string to uppercase | "hello".upper() |
"HELLO" |
| Case Conversion | lower() | Converts string to lowercase | "HELLO".lower() |
"hello" |
| Case Conversion | capitalize() | Capitalizes first character | "hello world".capitalize() |
"Hello world" |
| Case Conversion | title() | Capitalizes first character of each word | "hello world".title() |
"Hello World" |
| Case Conversion | swapcase() | Swaps case of all characters | "Hello World".swapcase() |
"hELLO wORLD" |
| Case Conversion | casefold() | More aggressive lowercase (for case-insensitive comparison) | "HELLO".casefold() |
"hello" |
| Search & Find | find() | Returns index of first occurrence, -1 if not found | "hello".find("e") |
1 |
| Search & Find | rfind() | Returns index of last occurrence, -1 if not found | "hello hello".rfind("e") |
7 |
| Search & Find | index() | Like find() but raises ValueError if not found | "hello".index("e") |
1 |
| Search & Find | rindex() | Like rfind() but raises ValueError if not found | "hello".rindex("l") |
3 |
| Search & Find | count() | Counts occurrences of substring | "hello".count("l") |
2 |
| Search & Find | startswith() | Checks if string starts with prefix | "hello".startswith("he") |
True |
| Search & Find | endswith() | Checks if string ends with suffix | "hello".endswith("lo") |
True |
| Modification | replace() | Replaces substring with another | "hello".replace("l", "x") |
"hexxo" |
| Modification | strip() | Removes leading/trailing whitespace | " hello ".strip() |
"hello" |
| Modification | lstrip() | Removes leading whitespace | " hello".lstrip() |
"hello" |
| Modification | rstrip() | Removes trailing whitespace | "hello ".rstrip() |
"hello" |
| Modification | zfill() | Pads string with zeros to specified width | "42".zfill(5) |
"00042" |
| Modification | center() | Centers string in specified width | "hi".center(10, "-") |
"----hi----" |
| Modification | ljust() | Left-justifies string in specified width | "hi".ljust(10, "-") |
"hi--------" |
| Modification | rjust() | Right-justifies string in specified width | "hi".rjust(10, "-") |
"--------hi" |
| Checking Methods | isalpha() | Checks if all characters are alphabetic | "hello".isalpha() |
True |
| Checking | isdigit() | Checks if all characters are digits | "123".isdigit() |
True |
| Checking | isalnum() | Checks if all characters are alphanumeric | "hello123".isalnum() |
True |
| Checking | isspace() | Checks if all characters are whitespace | " ".isspace() |
True |
| Checking | islower() | Checks if all characters are lowercase | "hello".islower() |
True |
| Checking | isupper() | Checks if all characters are uppercase | "HELLO".isupper() |
True |
| Checking | istitle() | Checks if string is titlecased | "Hello World".istitle() |
True |
| Checking | isnumeric() | Checks if all characters are numeric | "123".isnumeric() |
True |
| Checking | isdecimal() | Checks if all characters are decimal | "123".isdecimal() |
True |
| Formatting | format() | Formats string using placeholders | "{} {}".format("Hello", "World") |
"Hello World" |
| Formatting | format_map() | Formats string using dictionary mapping | "{name}".format_map({'name': 'John'}) |
"John" |
| Utility | split() | Splits string by delimiter into list | "a,b,c".split(",") |
["a", "b", "c"] |
| Utility | rsplit() | Splits string from right by delimiter | "a,b,c".rsplit(",", 1) |
["a,b", "c"] |
| Utility | splitlines() | Splits string at line breaks | "line1\nline2".splitlines() |
["line1", "line2"] |
| Utility | join() | Joins iterable elements with string as separator | ",".join(["a", "b", "c"]) |
"a,b,c" |
| Utility | partition() | Splits string at first occurrence of separator | "hello.world".partition(".") |
("hello", ".", "world") |
| Utility | rpartition() | Splits string at last occurrence of separator | "hello.world.py".rpartition(".") |
("hello.world", ".", "py") |
| Utility | expandtabs() | Replaces tabs with spaces | "hello\tworld".expandtabs(4) |
"hello world" |
| Utility | translate() | Maps characters using translation table | str.maketrans("ae", "12") |
Translation table |
| Utility | maketrans() | Creates translation table for translate() | "apple".translate(table) |
Translated string |
- String methods return new strings (strings are immutable)
- Use
inoperator for membership testing:'a' in 'apple' - Chain methods:
" Hello ".strip().lower().capitalize() find()returns -1 if not found,index()raises ValueError
String Formatting Methods
Python offers multiple ways to format strings: f-strings (Python 3.6+), format() method, and %-formatting.
# 1. f-strings (Python 3.6+) - RECOMMENDED
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is Alice and I'm 25 years old.
# Expressions in f-strings
a = 10
b = 20
print(f"The sum of {a} and {b} is {a + b}")
# Output: The sum of 10 and 20 is 30
# Formatting numbers
pi = 3.14159
print(f"Pi value: {pi:.2f}") # 2 decimal places
print(f"Pi value: {pi:.4f}") # 4 decimal places
# 2. format() method
print("My name is {} and I'm {} years old.".format(name, age))
print("My name is {1} and I'm {0} years old.".format(age, name))
print("My name is {name} and I'm {age} years old.".format(name=name, age=age))
# 3. %-formatting (older style)
print("My name is %s and I'm %d years old." % (name, age))
# 4. Advanced formatting
# Padding and alignment
print(f"{'Left':<10}") # Left-aligned in 10 chars
print(f"{'Center':^10}") # Center-aligned in 10 chars
print(f"{'Right':>10}") # Right-aligned in 10 chars
# Number formatting
number = 1234.5678
print(f"{number:,}") # 1,234.5678 (thousands separator)
print(f"{number:.2f}") # 1234.57 (2 decimal places)
print(f"{number:10.2f}") # Right-aligned in 10 chars, 2 decimals
# Binary, octal, hexadecimal
value = 255
print(f"Binary: {value:b}") # 11111111
print(f"Octal: {value:o}") # 377
print(f"Hex: {value:x}") # ff
print(f"HEX: {value:X}") # FF
String Operations & Slicing
Learn advanced string operations including slicing, concatenation, repetition, and membership testing.
# String concatenation
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(f"Concatenation: {result}") # Hello World
# String repetition
print(f"Repetition: {'Ha' * 3}") # HaHaHa
# String length
text = "Python Programming"
print(f"Length of '{text}': {len(text)}") # 18
# String membership testing
print(f"'Pro' in '{text}': {'Pro' in text}") # True
print(f"'Java' in '{text}': {'Java' in text}") # False
# String comparison
print(f"'apple' == 'apple': {'apple' == 'apple'}") # True
print(f"'apple' == 'Apple': {'apple' == 'Apple'}") # False
print(f"'apple' != 'orange': {'apple' != 'orange'}") # True
# Advanced slicing
text = "Python Programming"
# Basic slicing
print(f"text[0:6]: {text[0:6]}") # Python
print(f"text[7:]: {text[7:]}") # Programming
print(f"text[:6]: {text[:6]}") # Python
print(f"text[-11:]: {text[-11:]}") # Programming
# Step slicing
print(f"text[::2]: {text[::2]}") # Pto rgamn (every 2nd char)
print(f"text[1::2]: {text[1::2]}") # yhnPormig (every 2nd char starting from index 1)
# Reverse string
print(f"text[::-1]: {text[::-1]}") # gnimmargorP nohtyP
# Negative indexing
print(f"text[-1]: {text[-1]}") # g (last character)
print(f"text[-5:]: {text[-5:]}") # mming (last 5 characters)
# Slicing with negative step
print(f"text[10:4:-1]: {text[10:4:-1]}") # margo (reverse slice)
# Common string patterns
filename = "document.pdf"
# Check file extension
if filename.endswith(".pdf"):
print(f"{filename} is a PDF file")
# Remove file extension
name_without_ext = filename.rsplit(".", 1)[0]
print(f"Filename without extension: {name_without_ext}")
# Split path
path = "/home/user/documents/file.txt"
parts = path.split("/")
print(f"Path parts: {parts}") # ['', 'home', 'user', 'documents', 'file.txt']
Escape Sequences & Raw Strings
Escape sequences allow special characters in strings. Raw strings treat backslashes as literal characters.
# Escape sequences
print("Line 1\nLine 2") # New line
print("Tab\tseparated") # Tab
print("Backslash: \\") # Backslash
print("Single quote: \'") # Single quote
print("Double quote: \"") # Double quote
print("Carriage return: \r") # Carriage return
print("Backspace: Hello\bWorld") # Backspace
print("Form feed: \f") # Form feed
print("Vertical tab: \v") # Vertical tab
print("Octal value: \101") # Octal (A)
print("Hex value: \x41") # Hex (A)
# Raw strings (treat backslashes as literal)
print(r"C:\Users\Name\Documents") # C:\Users\Name\Documents
print(r"Newline: \n won't work") # Newline: \n won't work
# Multi-line strings
multi_line = """Line 1
Line 2
Line 3"""
print(multi_line)
# Multi-line with line continuation
long_string = ("This is a very long string that "
"spans multiple lines using "
"parentheses for line continuation.")
print(long_string)
String Practice Exercises
Try these exercises to test your understanding of Python strings.
# Python Strings Practice Exercises
print("=== Exercise 1: Basic String Operations ===")
# 1. Create a string with your name and print it in uppercase
name = "John Doe"
print(f"Name in uppercase: {name.upper()}")
# 2. Create a string with multiple words and count the spaces
sentence = "Python is a great programming language"
space_count = sentence.count(" ")
print(f"Spaces in sentence: {space_count}")
print("\n=== Exercise 2: String Manipulation ===")
# 3. Reverse a string without using [::-1]
text = "Python"
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print(f"Original: {text}, Reversed: {reversed_text}")
# 4. Check if a string is palindrome
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
test_strings = ["radar", "hello", "A man a plan a canal Panama"]
for s in test_strings:
print(f"'{s}' is palindrome: {is_palindrome(s)}")
print("\n=== Exercise 3: String Formatting ===")
# 5. Format personal information
person = {
"name": "Alice",
"age": 30,
"city": "New York",
"salary": 75000.50
}
# Using f-string
info = f"{person['name']} is {person['age']} years old, lives in {person['city']}, and earns ${person['salary']:.2f} per year."
print(f"Personal info: {info}")
print("\n=== Exercise 4: String Methods ===")
# 6. Clean and normalize user input
user_input = " HELLO World! "
cleaned = user_input.strip().lower().capitalize()
print(f"Original: '{user_input}'")
print(f"Cleaned: '{cleaned}'")
# 7. Extract domain from email
email = "user@example.com"
username, domain = email.split("@")
print(f"Email: {email}")
print(f"Username: {username}")
print(f"Domain: {domain}")
print("\n=== Exercise 5: Advanced Operations ===")
# 8. Find all vowels in a string
text = "Hello World"
vowels = "aeiouAEIOU"
vowel_count = sum(1 for char in text if char in vowels)
print(f"Text: '{text}'")
print(f"Vowel count: {vowel_count}")
# 9. Convert string to list of characters and back
text = "Python"
char_list = list(text)
print(f"String to list: {char_list}")
back_to_string = "".join(char_list)
print(f"List back to string: {back_to_string}")
# 10. Word frequency counter
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(f"\nWord frequencies: {word_count}")
Key Takeaways
- Python strings are immutable sequences of Unicode characters
- Use quotes: single (
'), double ("), or triple ('''/""") for multi-line - String indexing:
text[0]gets first character,text[-1]gets last - String slicing:
text[start:end:step]extracts substrings - 40+ built-in methods for case conversion, searching, formatting, validation
- f-strings (Python 3.6+) are the recommended formatting method
- Use
inoperator for membership testing:'a' in 'apple' find()returns -1 if not found;index()raises ValueError- Raw strings (
r"...") treat backslashes as literal characters - Common operations: concatenation (
+), repetition (*), length (len())