Python | Swap commas and periods in a line

Python Methods and Functions

The problem is pretty simple. For this line, we need to replace all commas with periods, and all periods — commas. This can be achieved in two popular ways. 
Examples:

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

Using maketrans and translate ()

maketrans: this static method returns the translation table used for str.translate () . This creates a translation table, which is a mapping of integers or characters to integers, strings, or None.

translate: returns a copy of the string in which all characters occurring in the optional argument , are removed, and the rest of the characters are displayed in the translation table specified in the maketrans table. 
For more information visit rstrip-min-max-maketrans-translate-relplace/ rel = noopener target = _blank> Python String Methods .

# Python code to replace. and vice versa

def Replace (str1):

maketrans = str1.maketrans

final = str1.translate (maketrans ( ', .' , '.,' ))

return final

 
# Driver's code

string = " 14, 625, 498.002 "

print (Replace (string))

Output:

 14.625.498, 002 

Using replace ()

This is a more logical approach, in which we change characters taking into account third variables. The replace method can also be used to replace methods in strings. We can convert "," to character, then convert "." In "," and the character in ".". For more information visit rstrip-min-max-maketrans-translate-relplace/ rel=noopener target=_blank> Python String Methods . 
Example:

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 




Tutorials