1 min read

    Python for DSA — Strings

    PythonDSAStringsSlicing

    2. Strings

    💡 Why this matters for DSA Strings appear in ~30% of DSA problems — palindromes, anagrams, pattern matching, substring searches. Mastering string operations is essential.


    2.1 Creating & Indexing

    Strings are immutable — you cannot change a character in place.

    python
    s = "hello"
    print(s[0])    # 'h'
    print(s[-1])   # 'o' (negative index = from end)
    print(s[4])    # 'o'
    
    # s[0] = 'H'   # ❌ Error! Strings are immutable
    

    ✅ Tip — String ↔ List conversion:

    python
    s = "hello"
    chars = list(s)      # ['h', 'e', 'l', 'l', 'o']
    chars[0] = 'H'
    s = "".join(chars)   # "Hello"
    

    2.2 Slicing

    One of Python's most powerful features for DSA.

    python
    s = "abcdef"
    
    s[1:4]       # "bcd"   (start:end — end exclusive)
    s[:3]        # "abc"   (start defaults to 0)
    s[3:]        # "def"   (end defaults to end)
    s[::2]       # "ace"   (step)
    s[::-1]      # "fedcba" (reverse — extremely common!)
    s[4:1:-1]    # "edc"   (negative step)
    

    ⚠️ Warning: Slicing creates a new string (O(n) time & space). For large strings, be mindful.


    2.3 Useful Methods

    python
    s = "  Hello World!  "
    
    s.lower()           # "  hello world!  "
    s.upper()           # "  HELLO WORLD!  "
    s.strip()           # "Hello World!"     (removes leading/trailing whitespace)
    s.split()           # ["Hello", "World!"] (splits on whitespace)
    s.split(",")        # split on specific delimiter
    ",".join(["a","b","c"])  # "a,b,c"
    s.replace("World", "Python")  # "  Hello Python!  "
    "hello" in s        # True (membership check — O(n) but very fast in C)
    s.count("l")        # 3
    s.startswith("  He") # True
    s.endswith("!  ")   # True
    

    ✅ Tip — .split() vs .join() in DSA:

    python
    # Splitting a sentence into words
    words = "hello world python".split()  # ["hello", "world", "python"]
    
    # Joining back
    sentence = " ".join(words)  # "hello world python"
    

    2.4 f-strings (Formatting)

    python
    name = "Manik"
    age = 25
    
    print(f"My name is {name} and I am {age} years old")
    print(f"Sum of {a} + {b} = {a + b}")    # expressions inside {}
    print(f"{value:.2f}")                    # 2 decimal places
    

    2.5 Character Operations

    python
    ord('a')       # 97   (char → ASCII)
    chr(97)        # 'a'  (ASCII → char)
    
    # Check character properties
    "abc".isalpha()    # True
    "123".isdigit()    # True
    "  ".isspace()    # True
    

    ✅ Tip — Common DSA pattern:

    python
    # Convert lowercase letter to 0-indexed position
    pos = ord('c') - ord('a')  # 2
    

    Practice Drill

    python
    # 1. Reverse a string
    # 2. Check if a string is a palindrome
    # 3. Count vowels in a string
    # 4. Remove all spaces from a string
    
    💡 Click for Solutions
    python
    # 1. Reverse
    s = "hello"
    print(s[::-1])  # "olleh"
    
    # 2. Palindrome
    s = "racecar"
    print(s == s[::-1])  # True
    
    # 3. Count vowels
    s = "hello world"
    vowels = "aeiou"
    count = sum(1 for ch in s if ch in vowels)
    print(count)  # 3
    
    # 4. Remove spaces
    s = "hello world python"
    print(s.replace(" ", ""))  # "helloworldpython"
    

    ← Basics | Next → Lists