Open In App

Python | Swap commas and dots in a String

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The problem is quite simple. Given a string, we need to replace all commas with dots and all dots with the commas. This can be achieved in many different ways. 
Examples: 

Input : 14, 625, 498.002
Output : 14.625.498, 002 

Method 1: Using maketrans and translate()

maketrans: This static method returns a translation table usable for str.translate(). This builds a translation table, which is a mapping of integers or characters to integers, strings, or None.
translate: This returns a copy of the string where all characters occurring in the optional argument are removed, and the remaining characters have been mapped through the translation table, given by the maketrans table. 
For more reference visit Python String Methods.  

Python3




# Python code to replace, with . and vice-versa
def Replace(str1):
    maketrans = str1.maketrans
    final = str1.translate(maketrans(',.', '.,', ' '))
    return final.replace(',', ", ")
 
 
# Driving Code
string = "14, 625, 498.002"
print(Replace(string))


Output

14.625.498, 002

Method 2: Using replace()

This is more of a logical approach in which we swap the symbols considering third variables. The replace method can also be used to replace the methods in strings. We can convert “, ” to a symbol then convert “.” to “, ” and the symbol to “.”. For more reference visit Python String Methods
Example:  

Python3




def Replace(str1):
    str1 = str1.replace(', ', 'third')
    str1 = str1.replace('.', ', ')
    str1 = str1.replace('third', '.')
    return str1
     
string = "14, 625, 498.002"
print(Replace(string))


Output

14.625.498, 002

Method 3: Using sub() of RegEx 

Regular Expression or RegEx a string of characters used to create search patterns. RegEx can be used to check if a string contains the specified search pattern. In python, RegEx has different useful methods. One of its methods is sub(). The complexity of this method is assumed to be O(2m +n), where m=length of regex, n=length of the string. 

The sub() function returns a string with values altered and stands for a substring. When we utilise this function, several elements can be substituted using a list.

Python3




import re
 
txt = "14, 625, 498.002"
x = re.sub(', ', 'sub', txt)
x = re.sub('\.', ', ', x)
x = re.sub('sub', '.', x)
print(x)
 
#contributed by prachijpatel1


Output

14.625.498, 002

Approach 4: Using split and join
 

Python3




#Approach 4: Using split and join
def Replace(str1):
    str1= "$".join(str1.split(', '))
    str1=', '.join(str1.split('.'))
    str1='.'.join(str1.split('$'))
    return str1
 
string = "14, 625, 498.002"
print(Replace(string))
#This code is contributed by Edula Vinay Kumar Reddy


Output

14.625.498, 002

Time Complexity: O(n), where n is the length of the input string
Auxiliary Space: O(n)

Approach 5: Using simple for loop and join method.

Steps- 

  1. Create an empty arr array .
  2. We will iterate the given input string character by character.
  3. While iterating the string, if we encounter ‘.’ character in string then we will append ‘, ‘ string in arr named array we created earlier.
  4. While iterating the string, if we encounter  ‘,’ character in string then we will append ‘.’ character in arr named array.
  5. While iterating the string, if we encounter  ‘ ‘ character in string then we skip the current iteration and move forward to next iteration.
  6. While iteration, if there is no character from 3,4,5 step in string, then append that character in the arr array.
  7. Then at the end of the iteration of string, convert array to string using ‘join’ string method.
  8. Required result is obtained and we replaced all commas with dots and all dots with the commas.

Below is the implementation of above approach:

Python3




# Python code to replace, with . and vice-versa
def Replace(str1):
    arr = []
     
    for i in str1:
        if (i == '.'):
            arr.append(', ')
        elif (i == ','):
            arr.append('.')
            continue
        elif (i == ' '):
            continue
        else:
            arr.append(i)
 
    str2 = ''.join(arr)
    return str2
 
# Driving Code
string = "14, 625, 498.002"
print(Replace(string))
 
# This code is contributed by Pratik Gupta


Output

14.625.498, 002

Time Complexity : O(n), where n is the length of the input string
Auxiliary Space : O(n), where n is the length of the input string

Approach 6: Using reduce():
Algorithm:

  1. Define a string variable ‘string’ with the input value.
  2. Define a list of tuples with the characters to be replaced and the replacement characters.
  3. Use the reduce() function with lambda function to iterate through each tuple in the list and replace the characters in the string.
  4. Return the final string with all the characters replaced.

Python3




from functools import reduce
 
string = "14, 625, 498.002"
result = reduce(lambda acc, char: acc.replace(char[0], char[1]), [('.', ', '), (', ', '.'), (' ', '')], string)
 
print(result)
#This code is contributed by Rayudu.


Output

14.625.498.002

Time Complexity: O(n), where n is the length of the input string. The time complexity of the reduce function is O(n).

Space Complexity: O(n), where n is the length of the input string. The space complexity of the input string and the result string is O(n).



Similar Reads

Print number with commas as 1000 separators in Python
In this program, we need to print the output of a given integer in international place value format and put commas at the appropriate place, from the right. Let's see an example of how to print numbers with commas as thousands of separators in Python. Examples Input : 1000000 Output : 1,000,000 Input : 1000 Output : 1,00Method 1: using f-string F-s
2 min read
Replace Commas with New Lines in a Text File Using Python
Replacing a comma with a new line in a text file consists of traversing through the file's content and substituting each comma with a newline character. In this article, we will explore three different approaches to replacing a comma with a new line in a text file. Replace Comma With a New Line in a Text FileBelow are the possible approaches to rep
2 min read
What is Three dots(...) or Ellipsis in Python3
Ellipsis is a Python Object. It has no Methods. It is a singleton Object i.e. , provides easy access to single instances. Various Use Cases of Ellipsis (...): Default Secondary Prompt in Python interpreter.Accessing and slicing multidimensional Arrays/NumPy indexing.In type hinting.Used as Pass Statement inside Functions.Default Secondary Prompt in
3 min read
Python Program to swap the First and the Last Character of a string
Given a String. The task is to swap the first and the last character of the string. Examples: Input: GeeksForGeeks Output: seeksForGeekG Input: Python Output: nythoP Python string is immutable which means we cannot modify it directly. But Python has string slicing which makes it very easier to perform string operations and make modifications. Follo
2 min read
Python - Swap elements in String list
Sometimes, while working with data records we can have a problem in which we need to perform certain swap operation in which we need to change one element with other over entire string list. This has application in both day-day and data Science domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using replace() + list
3 min read
Python3 Program for Swap characters in a String
Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your task is to find the final String after B swaps. Exam
5 min read
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values): One naive solution maybe something like just swa
4 min read
Python | Swap Name and Date using Group Capturing in Regex
In this article, we will learn how to swap Name and Date for each item in a list using Group Capturing and Numeric Back-referencing feature in Regex . Capturing Group : Parentheses groups the regex between them and captures the text matched by the regex inside them into a numbered group i.e ([\w ]+) which can be reused with a numbered back-referenc
3 min read
Python - Swap ith and jth key's value in dictionary
Given a dictionary, perform swapping of ith and jth index key's value. Input : test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "geeks": 10}, i, j = 1, 4 Output : {'Gfg': 2, 'is': 10, 'best': 7, 'for': 9, 'geeks': 4} Explanation : Values of "is" and "geeks" swapped.Input : test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "geeks": 10}, i, j
6 min read
Python Program to Swap Two Elements in a List
Given a list in Python and provided the positions of the elements, write a program to swap the two elements in the list. Examples: Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3Output : [19, 65, 23, 90] Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5Output : [1, 5, 3, 4, 2] Swap Two Elements in a List using comma assignment Since the positi
4 min read
Practice Tags :