Open In App

Python - Swap commas and dots in a String

Last Updated : 27 Dec, 2024
Suggest changes
Share
Like Article
Like
Report

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:

Python
# Create a translation table  # to map commas to dots and vice versa t = str.maketrans(',.', '.,') s = "14, 625, 498.002" # Swap commas and dots res = s.translate(t) print(res) 

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:

Python
s = "14, 625, 498.002" # Replace commas with a temporary character s = s.replace(',', '#') # Replace dots with commas s = s.replace('.', ',') # Replace the temporary character with dots s = s.replace('#', '.') print(s) 

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:

Python
import re s = "14, 625, 498.002" # Swap commas and dots with lambda function s = re.sub(r'[.,]', lambda x: ',' if x.group(0) == '.' else '.', s) print(s) 

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:

Python
s = "14, 625, 498.002" # Swap commas and dots  s = ''.join(['.' if char == ',' else ',' if char == '.' else char for char in s]) print(s) 

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:

Python
s = "14, 625, 498.002" # Initialize empty list to store result res = [] for char in s: # If character is comma, append dot if char == ',': res.append('.') # If character is dot, append comma elif char == '.': res.append(',') # Otherwise, append the character as is else: res.append(char) # Join list of characters back into string s = ''.join(res) print(s) 

Output
14. 625. 498,002 

Similar Reads

Practice Tags :