-1

I would like to know what is the regular expression to transform a string that starts with a minus sign, followed by a comma and a sequence of digits, such as -.13082, into a string that starts with a minus sign followed by the first digit of the previous sequence, followed by a dot and then the rest of the digits.

This would transform -.13082 to -1.3082 or -.26750 to -2.6750

thank you

Barmar
  • 741,623
  • 53
  • 500
  • 612
Zembla
  • 331
  • 1
  • 2
  • 9
  • Depending on your use case, wouldn't it be easier to convert to int, check if it's lower than 0, then multiplying by 10? (and maybe convert it back to string) – VvdL Jun 16 '23 at 15:50
  • 1
    This should be a simple use of capture groups and back-references in the replacement string. What have you tried? – Barmar Jun 16 '23 at 15:55
  • There's no comma in your strings. `.` is decimal point (or period, or full stop), `,` is comma. – Barmar Jun 16 '23 at 15:56
  • @Zembla The comment says "multiplying by 10", not "divide by 10" (`-.75` is a shorthand for `-0.75`). Be aware of [floating point maths](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) though. You might want to use the [`decimal`](https://docs.python.org/3/library/decimal.html) library. – 3limin4t0r Jun 16 '23 at 16:23
  • 1
    sorry Vvld and 3limin4t0r , with Vvld solution it's work. I receive the value in string format. But by converting it to a float and multiplying by 10, it works. Jules' regex solution also works (see below), but I need to test if the value is less than zero, so this solution is better for me. Thanks to everyone. – Zembla Jun 16 '23 at 16:43
  • Do you have basic knowledge of Regular Expressions ? What have you tried to get that knowledge to answer your own question ? – sln Jun 16 '23 at 21:35

2 Answers2

1

Use regex groups. One for the minus sign, one for the first digit, one for the remainder of the digits.

>>> re.sub(r'(-)\.(\d)(.*)', r'\1\2.\3',  "-.13082")
'-1.3082'
>>> re.sub(r'(-)\.(\d)(.*)', r'\1\2.\3', "-.26750")
'-2.6750'
Jules
  • 21
  • 2
1

You can use the following pattern with the re.sub method—swapping the . with the captured value.

\.(\d)
string = '-.13082'
string = re.sub(r'\.(\d)', r'\1.', string)
-1.3082

Alternately, if the locations are static, you can swap the character indices using a list class, and re-concatenate with str.join.

string = '-.13082'
chars = list(string)
chars[1], chars[2] = chars[2], chars[1]
string = ''.join(chars)
Reilas
  • 3,297
  • 2
  • 4
  • 17
  • Note that this would also convert `-9.876` into `-98.76`. To prevent that make sure there is no decimal before the point. `r'(?<!\d)\.(\d)'`. – 3limin4t0r Jun 19 '23 at 08:20
  • @3limin4t0r, well, of course. They had stated, _"... a string that starts with a minus sign, followed by a comma and a sequence of digits ..."_, though. – Reilas Jun 19 '23 at 14:56