+Python | Swap commas and dots in a String

Created with Sketch.

Python Program: Swap Commas and Dots in a String

In this blog post, we’ll explore a Python program that swaps commas and dots in a given string. The program will take a string as input, swap occurrences of commas (,) with dots (.) and vice versa, and then output the modified string. We’ll discuss the algorithm, provide a step-by-step explanation, present the Python code, and include examples with outputs.

Understanding the Algorithm

The algorithm for swapping commas and dots in a string involves the following steps:

  1. Input String: Take a string as input.

  2. Swap Commas and Dots: Iterate through each character in the string, and whenever a comma is encountered, replace it with a dot, and vice versa.

  3. Output Result: Display the modified string with swapped commas and dots.

Python Program for Swapping Commas and Dots

Let’s implement the algorithm in a Python program:

def swap_commas_dots(input_str):
    # Initialize an empty string to store the result
    result_str = ""

    # Iterate through each character in the input string
    for char in input_str:
        if char == ',':
            # Replace commas with dots
            result_str += '.'
        elif char == '.':
            # Replace dots with commas
            result_str += ','
        else:
            # Keep other characters unchanged
            result_str += char

    return result_str

# Input a string
input_string = input("Enter a string with commas and dots: ")

# Swap commas and dots, then display result
output_result = swap_commas_dots(input_string)
print(f"The modified string is: {output_result}")

Output Example

Example: Swap Commas and Dots

Let’s input the string "Python, Programming is fun.":

Input

Enter a string with commas and dots: Python, Programming is fun.

Output

The modified string is: Python. Programming is fun,

Explanation

The program defines a function swap_commas_dots that takes an input string and iterates through each character, swapping commas with dots and vice versa. The modified string is then displayed as the output.

Conclusion

This Python program demonstrates how to swap commas and dots in a given string. String manipulation is a common task in programming, and understanding how to modify strings can be beneficial in various applications. Feel free to test the program with different strings or incorporate it into larger projects.

If you have any questions or want to explore more Python programming topics, don’t hesitate to ask!

Leave a Reply

Your email address will not be published. Required fields are marked *