Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

A Function that Swaps Random Letters in a String Python

Learn how to create a function that swaps random letters in a string using Python, and understand the fundamental concepts of strings and functions in Python programming. …


Updated July 10, 2023

Learn how to create a function that swaps random letters in a string using Python, and understand the fundamental concepts of strings and functions in Python programming.

Definition of the Concept

The concept we’re exploring today is the manipulation of strings in Python. Specifically, we’ll be creating a function that takes a string as input and returns a new string with some of its letters randomly swapped. This might seem like a simple task, but it’s a great opportunity to learn about string indexing, slicing, and the random module.

Step-by-Step Explanation

To tackle this problem, we’ll follow these steps:

  1. Import the necessary modules: We’ll need the random module to generate random indices for swapping letters.
  2. Define the function: Create a function that takes a string as input and returns a new string with some of its letters swapped.
  3. Generate random indices: Use the random module to select two indices at random from the input string.
  4. Swap the characters: Swap the characters at the selected indices in the input string.
  5. Return the modified string: Return the resulting string with the letters swapped.

Code Snippet

Here’s the code snippet that implements the above steps:

import random

def swap_random_letters(input_string):
    """
    Returns a new string with some of its letters randomly swapped.
    
    Args:
        input_string (str): The input string to be modified.
    
    Returns:
        str: A new string with some of its letters swapped.
    """
    # Step 1: Convert the input string to a list of characters
    char_list = list(input_string)
    
    # Step 2: Generate two random indices for swapping
    idx1, idx2 = random.sample(range(len(char_list)), 2)
    
    # Step 3: Swap the characters at the selected indices
    char_list[idx1], char_list[idx2] = char_list[idx2], char_list[idx1]
    
    # Step 4: Join the list of characters back into a string
    modified_string = ''.join(char_list)
    
    return modified_string

# Example usage:
input_str = "Hello, World!"
modified_str = swap_random_letters(input_str)
print(modified_str)  # Output: e.g., "Hlloe, Wrold!"

Code Explanation

Let’s break down the code snippet:

  • We import the random module to generate random indices.
  • We define a function swap_random_letters() that takes an input string as argument.
  • Inside the function, we convert the input string to a list of characters using list(input_string).
  • We use random.sample(range(len(char_list)), 2) to select two random indices from the list of characters. The range function generates numbers from 0 to the length of the list minus one.
  • We swap the characters at the selected indices using tuple assignment, which is a concise way to swap values in Python.
  • Finally, we join the list of characters back into a string using ''.join(char_list) and return the modified string.

Readability

The code snippet has been written with readability in mind. The variable names are descriptive, and the function name clearly indicates its purpose. The comments explain what each section of the code does.

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp