[Coding Test] Essential Libraries

Lena JungLena Jung
3 min read

1. String Methods (Built-in Functions)

  1. Basic Operations:

    • len(s): Get the length of a string.

    • s[i]: Access the character at index i.

  2. Case Handling:

    • s.lower(), s.upper(): Convert to lowercase/uppercase.

    • s.capitalize(), s.title(): Capitalize the first character or each word.

    • s.swapcase(): Swap lowercase to uppercase and vice versa.

  3. String Search and Matching:

    • s.find(sub): Returns the first occurrence of sub or -1 if not found.

    • s.rfind(sub): Like find, but searches from the end.

    • s.count(sub): Count occurrences of a substring.

  4. String Manipulation:

    • s.strip(), s.lstrip(), s.rstrip(): Remove whitespace or specified characters.

    • s.replace(old, new): Replace all occurrences of old with new.

    • s.split(sep): Split a string into a list of substrings.

    • 'sep'.join(iterable): Join elements of an iterable with a string.

  5. Validation:

    • s.isdigit(), s.isalpha(), s.isalnum(): Check if the string is all digits, letters, or alphanumeric.

    • s.isspace(): Check if the string is only whitespace.

  6. Slicing and Reversing:

    • s[start:end:step]: Slice a string.

    • s[::-1]: Reverse a string.


2. Libraries for String Manipulation

  1. re (Regular Expressions):

    • Use for pattern matching and advanced text processing.

    • Common methods:

      • re.match(): Match a pattern at the start of a string.

      • re.search(): Search for a pattern anywhere in the string.

      • re.findall(): Find all occurrences of a pattern.

      • re.sub(): Replace matches with a substring.

    • Example:

        import re
        re.findall(r'\d+', 'abc123def456')  # ['123', '456']
      
  2. collections:

    • collections.Counter:

      • Count the frequency of characters or substrings.

      • Example:

          from collections import Counter
          Counter("aabbcc")  # Counter({'a': 2, 'b': 2, 'c': 2})
        
  3. string (String Constants):

    • Provides constants like string.ascii_letters, string.digits, string.punctuation.

    • Example:

        import string
        print(string.ascii_lowercase)  # abcdefghijklmnopqrstuvwxyz
      

3. Common Patterns to Know

  1. Check for Palindromes:

     def is_palindrome(s):
         s = s.lower().replace(" ", "")
         return s == s[::-1]
    
  2. Anagram Checking:

     def is_anagram(s1, s2):
         return sorted(s1) == sorted(s2)
    
  3. Longest Substring without Repeating Characters:

     def longest_unique_substring(s):
         seen = {}
         start = max_length = 0
         for i, c in enumerate(s):
             if c in seen and seen[c] >= start:
                 start = seen[c] + 1
             seen[c] = i
             max_length = max(max_length, i - start + 1)
         return max_length
    
  4. Count Words or Characters:

     from collections import Counter
     def word_count(s):
         words = s.split()
         return Counter(words)
    

4. Grammar Tips

  • List Comprehensions:

    • Simplify tasks like filtering or transforming strings:

        vowels = [c for c in "hello" if c in "aeiou"]
      
  • f-strings for Formatting:

    • Format strings dynamically:

        name = "Alice"
        print(f"Hello, {name}!")
      
  • Set for Unique Characters:

    • Quickly identify unique characters:

        unique_chars = set("abracadabra")  # {'a', 'b', 'r', 'c', 'd'}
      
  • Efficient String Iteration:

    • Use enumerate() to loop through a string with indices:

        for i, c in enumerate("hello"):
            print(i, c)
      
0
Subscribe to my newsletter

Read articles from Lena Jung directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lena Jung
Lena Jung