# Nakafa Framework: LLM
URL: /en/subject/university/bachelor/ai-ds/ai-programming/string-method
Source: https://raw.githubusercontent.com/nakafaai/nakafa.com/refs/heads/main/packages/contents/subject/university/bachelor/ai-ds/ai-programming/string-method/en.mdx
Output docs content for large language models.
---
export const metadata = {
    title: "String Methods",
    description: "Learn Python string methods for text manipulation. Master transformation, search, character validation, and advanced string operations.",
    authors: [{ name: "Nabil Akbarazzima Fatih" }],
    date: "09/17/2025",
    subject: "AI Programming",
};
## Immutable String Nature
Strings in Python have a special property called immutable, meaning that after a string is created, its contents cannot be changed directly. Imagine a string like a book that has already been printed, you cannot change words in it without reprinting the entire page.
When you try to change characters in a string directly, Python will display a TypeError. This is different from lists which can be modified element by element.
Although strings cannot be changed directly, you can create new strings based on old strings. Operations like concatenation with the `+` operator will produce new strings, not modify existing ones.
## Measuring String Length
The `len()` function is used to find out the number of characters in a string. Every character, including spaces and punctuation, is counted as one unit.
It's important to understand that escape sequences like `\n` and `\t` are counted as one character even though they are written with two symbols.
## String Transformation Methods
### Changing Letter Case
Python provides several methods to change the letter format in strings. Each method produces a new string with the desired format.
The `title()` method is very useful for formatting names or titles, where each word starts with a capital letter.
### Removing Characters at Start and End
Strip methods are useful for cleaning strings from unwanted characters at the beginning or end of strings.
Strip methods are very useful in data processing, especially when reading input from users or files that may contain extra spaces.
## Search and Validation Methods
### Finding Substring Position
The `index()` and `find()` methods are used to search for substring positions in strings. The difference lies in how they handle cases when the substring is not found.
Use `find()` when you're not sure if the substring exists in the string, and use `index()` when you're certain the substring definitely exists.
### String Character Validation
Python provides several methods to validate character types in strings.
These validation methods are very useful for verifying user input formats, such as phone numbers, postal codes, or usernames.
## Prefix and Suffix Search Methods
The `startswith()` and `endswith()` methods allow you to check if a string starts or ends with a specific substring.
Both methods support tuples as parameters, allowing checking of multiple prefixes or suffixes simultaneously.
## Replace and Split Methods
### Replacing Substrings
The `replace()` method is used to replace all occurrences of a substring with a new string.
The `replace()` method is case-sensitive and replaces all occurrences unless limited by the third parameter.
### Splitting Strings
The `split()` method breaks a string into a list based on a specified delimiter.
The `split()` method is very useful for processing structured data like CSV, parsing user input, or breaking file paths.
## String Method Chaining
Since each string method returns a new string, you can combine multiple methods in one expression. This is called method chaining.
 '{processed}'")`
    }
  ]}
/>
Method chaining makes code more concise and readable, especially when you need to perform several transformations consecutively on strings.
## Practical String Method Applications
String methods are often used in real programming scenarios to process and validate text data.
 '{formatted}'")
# 2. Extract information from filename
def analyze_filename(filename):
    # Separate name and extension
    if "." in filename:
        name, ext = filename.rsplit(".", 1)
        ext = ext.lower()
    else:
        name, ext = filename, ""
    
    # Analyze file type
    image_exts = ["jpg", "jpeg", "png", "gif", "bmp"]
    doc_exts = ["pdf", "doc", "docx", "txt"]
    code_exts = ["py", "js", "html", "css", "java"]
    
    if ext in image_exts:
        file_type = "Image"
    elif ext in doc_exts:
        file_type = "Document"
    elif ext in code_exts:
        file_type = "Code"
    else:
        file_type = "Unknown"
    
    return {
        "name": name,
        "extension": ext,
        "type": file_type,
        "length": len(filename)
    }
files = ["photo.jpg", "report.pdf", "script.py", "data", "image.PNG"]
for file in files:
    info = analyze_filename(file)
    print(f"{file}: {info}")
# 3. Simple log file parser
def parse_log_entry(log_line):
    # Format: [TIMESTAMP] LEVEL: MESSAGE
    if not log_line.strip():
        return None
    
    # Extract timestamp
    if log_line.startswith("[") and "]" in log_line:
        end_bracket = log_line.index("]")
        timestamp = log_line[1:end_bracket]
        rest = log_line[end_bracket + 1:].strip()
    else:
        timestamp = "Unknown"
        rest = log_line.strip()
    
    # Extract level
    if ":" in rest:
        level, message = rest.split(":", 1)
        level = level.strip()
        message = message.strip()
    else:
        level = "INFO"
        message = rest
    
    return {
        "timestamp": timestamp,
        "level": level,
        "message": message
    }
log_entries = [
    "[2023-09-17 10:30:15] ERROR: Database connection failed",
    "[2023-09-17 10:30:16] INFO: Retrying connection",
    "WARNING: Low disk space",
    ""
]
print("\\nLog parsing results:")
for entry in log_entries:
    parsed = parse_log_entry(entry)
    if parsed:
        print(f"Time: {parsed['timestamp']}, Level: {parsed['level']}, Message: {parsed['message']}")
# 4. URL slug generator from title
def create_slug(title):
    # Convert to lowercase and replace spaces with dash
    slug = title.lower()
    
    # Replace non-alphanumeric characters with dash
    clean_slug = ""
    for char in slug:
        if char.isalnum():
            clean_slug += char
        elif char == " " or not char.isalnum():
            if clean_slug and clean_slug[-1] != "-":
                clean_slug += "-"
    
    # Remove dashes at start and end
    return clean_slug.strip("-")
titles = [
    "Learn Python for Beginners",
    "Tips & Tricks Programming",
    "Data Science: Complete Guide",
    "Machine Learning 101"
]
print("\\nSlug generation:")
for title in titles:
    slug = create_slug(title)
    print(f"'{title}' -> '{slug}'")`
    }
  ]}
/>
These four application examples demonstrate the power of combining string methods to solve real-world problems. Method chaining enables complex string transformations in a single line of code, while the immutable nature of strings ensures safe and predictable operations.
By mastering these methods, you can build applications that handle input validation, data parsing, and text transformation efficiently.