VOOZH about

URL: https://www.geeksforgeeks.org/python/python-swap-commas-dots-string/

⇱ Python - Swap commas and dots in a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Swap commas and dots in a String

Last Updated : 27 Dec, 2024

In this article, we'll explore how to swap commas and dots in a string in Python.

Using str.translate()

str.translate() that allows for character substitution within a string using a translation table. It enables quick transformations, such as swapping characters like commas and dots.

Example:


Output
14. 625. 498,002

Let's understand different methods to swap commas and dots in a string.

Using str.replace()

str.replace() allows us to swap characters by first replacing them with a temporary placeholder. This approach enables efficient swapping of commas and dots in a string without direct mapping.

Example:


Output
14. 625. 498,002

Using regular expression

re.sub() uses regular expressions for flexible text replacements. By applying a callback function, it efficiently swaps commas and dots based on their context.

Example:


Output
14. 625. 498,002

Using List comprehension

List comprehension iterate over the string and swap commas and dots. The modified characters are then joined back into a string using join().

Example:


Output
14. 625. 498,002

Using for Loop

Loop iterate through the string and manually swap commas and dots. Characters are added to a list and then joined to form the final string.

Example:


Output
14. 625. 498,002
Comment