Swap Commas With Dots in Python

This article discusses three methods that can be used to replace commas with dots in a Python string. These methods include:

  1. Using str.replace() function,
  2. Using str.maketrans and str.translate(), and
  3. Using a find-and-replace strategy in a loop

The code examples in this article can be executed in Python 2 or Python 3.

Method 1: Using str.replace() function

The function str.replace(substring1, substring2) returns a copy of str will all occurrences of substring1 are replaced by substring2.

In this method, we need a third character (not a dot or a comma) that will be used to replace the first character (dot or comma) at the start to ensure that there’s no conflict when replacing. The third character should not be present in the string we are processing.

Example,

Output:

10,145.68

Method 2: Using str.maketrans and str.translate()

The str.maketrans is a static method that returns a mapping/translation table that can be used with the str.translate() function to replace specified characters.

Output:

10,145.68

Method 3: Using a dictionary find-and-replace strategy

In this method, we need to understand the use of dict.get(key[, default]) method. The function returns the value for the key if the key is in the dictionary, else default. Example,

Output:

smith
99

Once that is clear, we can work on an example of swapping commas with dots.

Output:

10,145.68