user3222101
user3222101

Reputation: 1330

How to replace a part of substring in Python?

I have a text like

"Euro Style = $12,345,67, US Style = $12,345,67, $1,234"

and I want to replace the string to

Output:

Euro Style = $12,345.67, US Style = $12,345.67, $1,234

i.e. whenever a currency is there, replace comma with dot when currency has 2 digits at the end.

I tried using regex, but somehow I am missing something.

add = "Euro Style = $12,345,67, US Style = $12,345,67, $1,234"
print(re.sub(r'([,][0-9]{2,}\B)+','.\2',add)) 

I am getting incorrect output as

Euro Style = $12.5,67, US Style = $12.5,67, $1.4

Upvotes: 0

Views: 62

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use

re.sub(r'(?<=\d),(?=\d{1,2}(?!\d))', r'.', s)

See the regex demo.

Details

  • (?<=\d) - a digit must be right before the...
  • , - comma that should be followed with...
  • (?=\d{1,2}(?!\d)) - 1 or 2 digits (\d{1,2}) not followed with another digit ((?!\d)).

Python test:

import re
s="Euro Style = $12,345,67, US Style = $12,345,67, $1,234, $12,124,345,456 $0,89  $12,345,678"
print(re.sub(r'(?<=\d),(?=\d{1,2}(?!\d))', '.', s))
# => Euro Style = $12,345.67, US Style = $12,345.67, $1,234, $12,124,345,456 $0.89  $12,345,678

Note that in case your numbers are never glued to _ or letters, you may also use a little simpler regex with a word boundary:

(?<=\d),(?=\d{1,2}\b)
                  ^^ 

See this regex demo.

Or even - if you do not care if there is a digit before , or not:

re.sub(r',(\d{1,2})\b', r'\1', s)

See this regex demo.

And finally, if you need to also change $12,212,12345678 to $12,212.12345678

re.sub(r',(\d{1,2}|\d{4,})\b', r'.\1', s)

See yet another regex demo.

The (\d{1,2}|\d{4,}) is an alternation group that matches either 1 or 2 digits or more than 4 digits, thus eliminating 3 digit chunks followed with a word boundary.

Upvotes: 1

KBN
KBN

Reputation: 153

Try

re.sub(r',(\d{2}\D)', r'.\1', add)

{2,} indicates 2 or more numbers. As you want to match exactly 2, you need to give {2}. Using \D just to match anything else apart from a digit. Hope this helps! –

Upvotes: 1

Related Questions