Python | Swap commas and dots in a String

Python | Swap commas and dots in a String

To swap commas and dots in a string, you can use the str.translate() method in combination with str.maketrans() to define a translation table. Here's how you can do it:

def swap_commas_dots(s): # Create a translation table trans = str.maketrans(',.', '.,') return s.translate(trans) # Test input_string = "Hello, how are you? I hope 3,000.50 dollars is enough." output_string = swap_commas_dots(input_string) print(output_string) 

Output:

Hello. how are you? I hope 3.000,50 dollars is enough, 

The str.maketrans() function creates a translation table where , is replaced with . and . is replaced with ,. The str.translate() method then uses this table to swap commas and dots in the input string.


More Tags

overlay spring-integration equality bearer-token firefox functional-dependencies nginx-config counter hudson-api beautifulsoup

More Programming Guides

Other Guides

More Programming Examples