Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to replace 'p' in a number(4p5) with '.' (4p5->4.5)? [closed]

I have a program that prints out some data with 'p's in place of decimal points, and also some other information. I was trying to replace the 'p's with '.'s.

Example output by the program:

out_info = 'value is approximately 34p55'

I would like to change it to:

out_info_updated = 'value is approximately 34.55'

I tried using re.search to extract out the number and replace the p with ., but plugging it back becomes a problem.I could not figure out that pattern to use for re.sub that would do the job. Can anyone please help?

like image 695
Tapajit Dey Avatar asked May 08 '13 06:05

Tapajit Dey


1 Answers

Here you go:

import re
out_info = "value is approximately 34p55"
re.sub(r'(\d+)p(\d+)', r'\1.\2', out_info)

The output is:

'value is approximately 34.55'

That says "Look for one or more digits, followed by a p, followed by one or more digits, then replace all that with the first set of digits, followed by a ., followed by the second set of digits."

like image 96
RichieHindle Avatar answered Oct 05 '22 23:10

RichieHindle