0

Is there any simple way to swap character of string in python. In my case I want to swap . and , from 5.123.673,682. So my string should become 5,123,673.682.

I have tried:

number = '5.123.673,682'
number = number.replace('.', 'temp')
number = number.replace(',', '.')
number = number.replace('temp', ',')
print(number) # 5,123,673.682

Thanks

2
  • I think that what you have done is the simplest way to accomplish this. Commented Nov 23, 2020 at 7:39
  • maybe as simple as like variable swap x,y=y,x Commented Nov 23, 2020 at 7:45

3 Answers 3

3

One way using dict.get:

mapper = {".": ",", ",":"."}

"".join([mapper.get(s, s) for s in '5.123.673,682'])

Or using str.maketrans and str.translate:

'5.123.673,682'.translate(str.maketrans(".,", ",."))

Output:

'5,123,673.682'
Sign up to request clarification or add additional context in comments.

Comments

0

This is a pythonic and clean approach to do that

def swap(c):
  if c == ',': return '.'
  elif c == '.': return ','
  else: return c

number = '5.123.673,682'
new_number = ''.join(swap(o) for o in number)

Comments

0

If you only need to swap single characters, think of it as a mapping instead

def mapping(c):
  if c == ',': return '.'
  if c == '.': return ','
  return c

number = '5.123.673,682'
converted = ''.join(map(mapping, number))
print(converted)

5,123,673.682

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.