Python Programming Strings
40+ Methods Slicing

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()

1. Introduction to Strings

In Python, strings are sequences of characters used to store text. Strings are immutable, meaning once created, they cannot be changed.

2. Creating Strings

Creating strings
# Single quotes
name = 'John Doe'

# Double quotes
message = "Hello World"

# Triple quotes (multi-line strings)
paragraph = """This is a
multi-line string
spanning multiple lines"""

# Using single quotes inside double quotes
text = "It's a beautiful day"

# Using double quotes inside single quotes
text2 = 'He said "Hello" to me'

# Empty string
empty = ""

# Strings from other types
number_str = str(123)        # "123"
float_str = str(3.14159)     # "3.14159"
bool_str = str(True)         # "True"

3. Accessing String Characters

Indexing
text = "Python"

# Positive indexing (0-based)
print(text[0])    # P
print(text[1])    # y
print(text[3])    # h

# Negative indexing (from end)
print(text[-1])   # n (last character)
print(text[-2])   # o
print(text[-3])   # h

# Strings are immutable - this causes error
# text[0] = 'J'  # TypeError: 'str' object does not support item assignment

4. String Slicing

Slicing syntax [start:end:step]
text = "Programming"

# Syntax: [start:end:step]
# start - included, end - excluded

print(text[0:4])     # "Prog" (indices 0,1,2,3)
print(text[4:8])     # "rami"
print(text[:4])      # "Prog" (from start)
print(text[4:])      # "ramming" (to end)
print(text[:])       # "Programming" (full copy)
print(text[::2])     # "Pormig" (every 2nd character)
print(text[1::2])    # "rgamn" (every 2nd starting from index 1)

# Negative slicing
print(text[-4:])     # "ming" (last 4 characters)
print(text[-8:-4])   # "gram"
print(text[::-1])    # "gnimmargorP" (reverse string)

5. String Operations

Concatenation

Concatenation
# Using + operator
greeting = "Hello" + " " + "World"
print(greeting)  # "Hello World"

# Using join() method
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)  # "Python is awesome"

Repetition

Repetition
# Using * operator
stars = "*" * 10
print(stars)     # "**********"

line = "-=" * 5
print(line)      # "-=-=-=-=-="

Length

Length
text = "Python Programming"
print(len(text))  # 19 (including space)

Membership Testing

Membership
text = "Hello World"

print("Hello" in text)    # True
print("hello" in text)    # False (case sensitive)
print("XYZ" not in text)  # True

Comparison

Lexicographic comparison
# String comparison is lexicographic (dictionary order)
print("apple" < "banana")    # True (a comes before b)
print("Apple" < "apple")     # True (uppercase < lowercase in ASCII)
print("abc" == "abc")        # True
print("abc" != "def")        # True

6. String Methods

Case Conversion

Case conversion
text = "python Programming TUTORIAL"

print(text.upper())      # "PYTHON PROGRAMMING TUTORIAL"
print(text.lower())      # "python programming tutorial"
print(text.capitalize()) # "Python programming tutorial"
print(text.title())      # "Python Programming Tutorial"
print(text.swapcase())   # "PYTHON pROGRAMMING tutorial"

# Check case
print("HELLO".isupper())    # True
print("hello".islower())    # True
print("Hello".istitle())    # True

Searching and Replacing

find, index, count, replace
text = "The quick brown fox jumps over the lazy dog"

# Find (returns index or -1)
print(text.find("fox"))      # 16
print(text.find("cat"))      # -1
print(text.rfind("the"))     # 35 (search from right)

# Index (like find but raises ValueError if not found)
print(text.index("fox"))     # 16
# print(text.index("cat"))   # ValueError

# Count occurrences
print(text.count("o"))       # 4
print(text.count("the"))     # 1

# Replace
print(text.replace("fox", "cat"))     # "The quick brown cat jumps over the lazy dog"
print(text.replace(" ", "_"))         # "The_quick_brown_fox_jumps_over_the_lazy_dog"
print(text.replace("o", "0", 2))      # "The quick br0wn f0x jumps over the lazy dog"

Removing Whitespace

strip, lstrip, rstrip
text = "   Hello World   "

print(text.strip())      # "Hello World" (removes both ends)
print(text.lstrip())     # "Hello World   " (removes left)
print(text.rstrip())     # "   Hello World" (removes right)

text2 = "---Python---"
print(text2.strip("-"))  # "Python"

Splitting and Joining

split, partition, join
# Split
text = "apple,banana,orange,grape"
fruits = text.split(",")
print(fruits)  # ['apple', 'banana', 'orange', 'grape']

text2 = "one two three four"
words = text2.split()
print(words)   # ['one', 'two', 'three', 'four']

text3 = "a,b,c,d"
print(text3.split(",", 2))  # ['a', 'b', 'c,d'] (split 2 times)

# Partition - splits at first occurrence
text4 = "name:John"
print(text4.partition(":"))  # ('name', ':', 'John')
print(text4.rpartition(":")) # ('name', ':', 'John') (from right)

# Join
delimiter = "-"
result = delimiter.join(["2024", "12", "25"])
print(result)  # "2024-12-25"

words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)  # "Python is fun"

Checking String Content

Validation helpers
# Alphanumeric checks
print("Hello123".isalnum())    # True (letters and numbers)
print("Hello 123".isalnum())   # False (space not allowed)
print("Hello".isalpha())       # True (only letters)
print("12345".isdigit())       # True (only digits)
print("123abc".isdigit())      # False
print("    ".isspace())        # True (only whitespace)

# Other checks
print("Hello".isascii())       # True (ASCII characters)
print("Hello123".isidentifier()) # True (valid Python identifier)
print("123".isdecimal())       # True (decimal numbers)
print("一二三".isnumeric())     # True (numeric characters)

Padding and Alignment

center, ljust, rjust, zfill
text = "Python"

# Center
print(text.center(20))          # "      Python       "
print(text.center(20, "*"))     # "*******Python*******"

# Left align
print(text.ljust(20))           # "Python              "
print(text.ljust(20, "-"))      # "Python--------------"

# Right align
print(text.rjust(20))           # "              Python"
print(text.rjust(20, "-"))      # "--------------Python"

# Zero fill
print("42".zfill(5))            # "00042"
print("-42".zfill(5))           # "-0042"
Next: See the complete string methods reference table below for every method at a glance.

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
Quick Tip:
  • String methods return new strings (strings are immutable)
  • Use in operator for membership testing: 'a' in 'apple'
  • Chain methods: " Hello ".strip().lower().capitalize()
  • find() returns -1 if not found, index() raises ValueError

7. String Formatting

f-strings (Python 3.6+)

f-strings
name = "Alice"
age = 30
height = 5.6

# Basic f-string
print(f"Name: {name}, Age: {age}")  # "Name: Alice, Age: 30"

# Expressions inside {}
print(f"Next year: {age + 1}")       # "Next year: 31"
print(f"Square of 5: {5**2}")         # "Square of 5: 25"

# Formatting numbers
print(f"Pi: {3.14159:.2f}")          # "Pi: 3.14"
print(f"Percentage: {0.75:.1%}")      # "Percentage: 75.0%"
print(f"Number: {42:05d}")           # "Number: 00042"

# Alignment
print(f"{'Left':<10}")    # "Left      "
print(f"{'Right':>10}")   # "     Right"
print(f"{'Center':^10}")  # "  Center  "

format() Method

str.format
# Positional arguments
print("{} {} {}".format("Python", "is", "fun"))     # "Python is fun"
print("{1} {0} {2}".format("Python", "is", "fun"))  # "is Python fun"

# Keyword arguments
print("{name} is {age} years old".format(name="Bob", age=25))

# Dictionary unpacking
data = {"name": "Charlie", "age": 35}
print("{name} is {age} years old".format(**data))

# Formatting specifiers
print("{:.2f}".format(3.14159))    # "3.14"
print("{:05d}".format(42))         # "00042"
print("{:>10}".format("right"))    # "     right"

Old-style Formatting (%)

% formatting
# %s - string, %d - integer, %f - float
name = "David"
age = 28
height = 5.9

print("Name: %s, Age: %d" % (name, age))           # "Name: David, Age: 28"
print("Height: %.2f" % height)                    # "Height: 5.90"
print("Hex: %x" % 255)                            # "Hex: ff"

8. Escape Characters

Common escape sequences
# Common escape sequences
print("Hello\nWorld")     # New line
print("Hello\tWorld")     # Tab
print("Hello\\World")     # Backslash
print("Hello\"World\"")   # Double quote
print("Hello\'World\'")   # Single quote
print("Hello\rWorld")     # Carriage return
print("Hello\bWorld")     # Backspace
print("Hello\fWorld")     # Form feed

# Raw strings (ignore escape sequences)
print(r"C:\Users\Name\Documents")  # "C:\Users\Name\Documents"
print(r"Hello\nWorld")             # "Hello\nWorld" (not line break)

9. Raw Strings

Raw strings with r prefix
# Raw strings are prefixed with 'r' or 'R'
# They treat backslashes as literal characters

# Normal string
normal = "C:\\Users\\Name\\file.txt"

# Raw string (cleaner)
raw = r"C:\Users\Name\file.txt"

print(normal)  # "C:\Users\Name\file.txt"
print(raw)     # "C:\Users\Name\file.txt"

# Useful for regex patterns
import re
pattern = r"\d+"  # Matches one or more digits

10. Common String Operations

Iterating Through Strings

Iteration
text = "Python"

# Method 1: Direct iteration
for char in text:
    print(char)

# Method 2: With index
for i in range(len(text)):
    print(f"Index {i}: {text[i]}")

# Method 3: enumerate
for i, char in enumerate(text):
    print(f"Index {i}: {char}")

Checking Prefixes and Suffixes

startswith, endswith
filename = "document.pdf"
url = "https://python.org"

print(filename.startswith("doc"))    # True
print(filename.endswith(".pdf"))     # True
print(url.startswith("https"))       # True

# With tuple of options
print(filename.endswith((".txt", ".pdf", ".doc")))  # True

Character Operations

ord and chr
# Get ASCII/Unicode value
print(ord('A'))    # 65
print(ord('a'))    # 97

# Get character from ASCII value
print(chr(65))     # 'A'
print(chr(97))     # 'a'

String Reversal

Reverse
text = "Python"

# Using slicing
reversed_text = text[::-1]
print(reversed_text)  # "nohtyP"

# Using reversed() and join
reversed_text2 = ''.join(reversed(text))
print(reversed_text2)  # "nohtyP"

11. Practical Examples

Example 1: Email Validation (Basic)

validate_email
def validate_email(email):
    # Check for @ and .
    if '@' not in email or '.' not in email:
        return False
    
    # Split into local and domain parts
    local, domain = email.split('@')
    
    # Check conditions
    if len(local) == 0 or len(domain) < 3:
        return False
    
    if '.' not in domain:
        return False
    
    return True

print(validate_email("user@example.com"))    # True
print(validate_email("invalid-email"))       # False

Example 2: Password Strength Checker

check_password_strength
def check_password_strength(password):
    score = 0
    feedback = []
    
    # Length check
    if len(password) >= 8:
        score += 1
    else:
        feedback.append("Password should be at least 8 characters")
    
    # Contains uppercase
    if any(char.isupper() for char in password):
        score += 1
    else:
        feedback.append("Add uppercase letters")
    
    # Contains lowercase
    if any(char.islower() for char in password):
        score += 1
    else:
        feedback.append("Add lowercase letters")
    
    # Contains digits
    if any(char.isdigit() for char in password):
        score += 1
    else:
        feedback.append("Add numbers")
    
    # Contains special characters
    special_chars = "!@#$%^&*"
    if any(char in special_chars for char in password):
        score += 1
    else:
        feedback.append("Add special characters")
    
    # Rating
    if score == 5:
        rating = "Strong"
    elif score >= 3:
        rating = "Medium"
    else:
        rating = "Weak"
    
    return rating, feedback

password = "Python@123"
rating, feedback = check_password_strength(password)
print(f"Password strength: {rating}")
if feedback:
    print("Suggestions:")
    for tip in feedback:
        print(f"  - {tip}")

Example 3: Text Wrapper

wrap_text
def wrap_text(text, width=50):
    """Wrap text to specified width"""
    words = text.split()
    lines = []
    current_line = []
    current_length = 0
    
    for word in words:
        if current_length + len(word) + 1 <= width:
            current_line.append(word)
            current_length += len(word) + 1
        else:
            lines.append(' '.join(current_line))
            current_line = [word]
            current_length = len(word) + 1
    
    if current_line:
        lines.append(' '.join(current_line))
    
    return '\n'.join(lines)

long_text = """Python is an interpreted high-level general-purpose programming language. 
Its design philosophy emphasizes code readability with its use of significant indentation."""

wrapped = wrap_text(long_text, 40)
print(wrapped)

Example 4: String to Title Case (Custom)

custom_title
def custom_title(text):
    """Convert string to title case without using title()"""
    result = []
    new_word = True
    
    for char in text:
        if char.isspace():
            result.append(char)
            new_word = True
        else:
            if new_word:
                result.append(char.upper())
                new_word = False
            else:
                result.append(char.lower())
    
    return ''.join(result)

print(custom_title("hello world"))        # "Hello World"
print(custom_title("python is FUN"))      # "Python Is Fun"

Example 5: Palindrome Checker

is_palindrome
def is_palindrome(text):
    # Remove spaces and convert to lowercase
    cleaned = ''.join(text.lower().split())
    
    # Check if equals its reverse
    return cleaned == cleaned[::-1]

# Test
words = ["racecar", "hello", "A man a plan a canal panama", "Python"]
for word in words:
    print(f"'{word}' is palindrome: {is_palindrome(word)}")

Key Takeaways

  • Strings are immutable — You cannot change individual characters
  • Indexing starts at 0 — First character is at position 0
  • Slicing creates new strings[start:end:step]
  • Many built-in methods — Strings have rich functionality
  • Multiple formatting options — f-strings, format(), %-formatting
  • Triple quotes for multi-line — Maintains line breaks
  • Raw strings for paths/regex — Use r prefix

Common String Pitfalls

Pitfalls
# Strings are immutable
text = "Hello"
# text[0] = "J"  # ERROR!

# Create new string instead
text = "J" + text[1:]  # "Jello"

# Case sensitivity
print("Hello".find("hello"))  # -1 (not found)

# strip() removes from both ends only
text = "  Hello World  "
print(text.strip())        # "Hello World"
print(text.replace(" ", ""))  # "HelloWorld"