w3resource

Python: Swap comma and dot in a string


Swap commas and dots in a string.

Write a Python program to swap commas and dots in a string.

Python String Exercises: Swap comma and dot in a string

Sample Solution:

Python Code:

# Define a string 'amount' with a numerical value in a specific format.
amount = "32.054,23"

# Create a variable 'maketrans' that references the 'maketrans' method of the 'amount' string.
maketrans = amount.maketrans

# Translate (replace) the characters ',' with '.', and '.' with ',' in the 'amount' string using the 'maketrans' variable.
amount = amount.translate(maketrans(',.', '.,'))

# Print the modified 'amount' string with the swapped decimal and comma characters.
print(amount) 

Sample Output:

32,054.23                  

Flowchart:

Flowchart: Swap comma and dot in a string

For more Practice: Solve these Related Problems:

  • Write a Python program to swap every comma with a dot and every dot with a comma in a given string.
  • Write a Python program to implement a function that iterates through a string and interchanges commas and periods.
  • Write a Python program to use regular expressions to find commas and dots and swap them in the output string.
  • Write a Python program to convert the input string into a list of characters, swap commas and dots, and then reassemble the string.

Go to:


Previous: Write a Python program to lowercase first n characters in a string.
Next: Write a Python program to count and display the vowels of a given text.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.