Skip to content

Write a Python program to swap commas and dots in a string | Example

  • by

You can Swap commas and dots in a String using replace() function or Using maketrans and translate() functions in Python.

Python program to swap commas and dots in a string Example

Simple example code to swap comma and dot in a string.

Using maketrans and translate()

It should swap commas and dots in the given string.

amount = "12.345,678"
maketrans = amount.maketrans
amount = amount.translate(maketrans(',.', '.,'))
print(amount)

Output:

Using replace()

With replacing method can convert “,” comma to a symbol then convert “.” dot to “,” comma and the symbol to “.” dot.

amount = "12.345,678"


def swap(str1):
    str1 = str1.replace(',', 'third')
    str1 = str1.replace('.', ', ')
    str1 = str1.replace('third', '.')
    return str1


print(swap(amount))

Output: 12, 345.678

Do comments if you have any doubts and suggestions on this Python swap code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading