The Wayback Machine - https://web.archive.org/web/20241001190951/https://www.geeksforgeeks.org/python-swap-commas-dots-string/
Open In App

Python | Swap commas and dots in a String

Last Updated : 23 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 | 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
Pandas DataFrame transpose() Method: Swap Rows and Columns
Pandas DataFrame is a two-dimensional, size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dictionary-like container for the Series objects. This is the primary data structure of the Pandas. Pandas DataFrame transpos
4 min read
How to swap columns of a given NumPy array?
In this article, let's discuss how to swap columns of a given NumPy array. Approach : Import NumPy moduleCreate a NumPy arraySwap the column with IndexPrint the Final array Example 1: Swapping the column of an array. C/C++ Code # importing Module import numpy as np # creating array with shape(4,3) my_array = np.arange(12).reshape(4, 3) print("
2 min read
How to Swap Two Rows in a NumPy Array
One common task you might encounter when working with NumPy arrays is the need to swap two rows. Swapping rows can be essential in data preprocessing, reshaping data, or reordering data to perform specific analyses in Python. In this article, we will explore different methods to swap two rows in a NumPy array. In this article, we will see how to sw
4 min read
Swap Two Variables in One Line
We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write "x, y = y, x".2) C/C++: Below is one generally provided classical solution: //
4 min read
NumPy ndarray.byteswap() Method | Swap bytes of the Array Elements
The ndarray.byteswap() method swaps the bytes of the array elements. It toggles between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Note: byteswap() method does not work on arrays of strings. Example C/C++ Code # Python program explaining # byteswap() function import numpy as geek # a
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: [GFGTABS] Python string = "Geeksforgeeks" print(len(string)) [/GFGTABS]Output13String len() Syntaxlen(string) ParameterString: string of which you want to find the length. Retu
5 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Lexicographically smallest string which is not a subsequence of given string
Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S. Examples: Input: S = "abcdefghijklmnopqrstuvwxyz"Output: aaExplanation:String "aa" is the lexicographically smallest string which is not present in the given string as a subsequence. Input: S = "aaaa"Output: aaabExplanat
5 min read
Sum of frequencies of characters of a string present in another string
Given two strings S1 and S2 of lengths M and N respectively, the task is to calculate the sum of the frequencies of the characters of string S1 in the string S2. Examples: Input: S1 = "pPKf", S2 = "KKKttsdppfP"Output: 7Explanation:The character 'p' occurs twice in the string S2.The character 'P' occurs once in the string S2.The character 'K' occurs
5 min read
Check if a string can be repeated to make another string
Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1. Examples: Input: a = "geeks", b = "geeksgeeks" Output: 2 "geeks" can be repeated twice to generate "geeksgeeks" Input: a = "df", b = "dfgrt" Output: -1 Recommended: Please try y
9 min read
Python | Count and display vowels in a string
In this program, we need to count the number of vowels present in a string and display those vowels. This can be done using various methods. In this article, we will go through few of the popular methods to do this in an efficient manner. Examples: In a simple way Input : Geeks for Geeks Output : 5 ['e', 'e', 'o', 'e', 'e'] This is in a different w
6 min read
String rjust() and ljust() in python()
1. String rjust() The string rjust() method returns a new string of given length after substituting a given character in left side of original string. Syntax: string.rjust(length, fillchar) Parameters: length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned. fillch
2 min read
Python - Convert Image to String and vice-versa
To store or transfer an Image to some we need to convert it into a string such that the string should portray the image which we give as input. So In Python to do this Operation, it is a straight forward task not complicated because we have a lot of functions in Python available. Convert Image To StringHere First We Import "Base64" Method To Encode
2 min read
Difference between %s and %d in Python string
In this article, we will see the difference between %s and %d in Python. Here, we start with the proper explanation of one at a time, then both, and at last compare these. What does %s do in Python? The % symbol is used in Python with a large variety of data types and configurations. It is used as an argument specifier and string formatter. %s spec
3 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 min read
How to Print String and Int in the Same Line in Python
Printing both texts and integers on the same line is a common chore for programmers. Python, fortunately, has various methods for accomplishing this, making it simple to display a combination of text and numerical values in your output. In this article, we'll explore various ways to print strings and integers in the same line in Python. Print Strin
2 min read
Split and Parse a string in Python
In Python, working with strings is a fundamental aspect of programming. Strings are sequences of characters and often contain structured data that needs to be processed or analyzed. The common operations performed on strings are splitting and parsing. Splitting a String in PythonIn Python, you can split a string into smaller parts using the split()
5 min read
How to split a string in C/C++, Python and Java?
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. In C: // Splits str[] according to given delimiters.// and returns next token. It needs to be ca
7 min read
Practice Tags :