Flux Capacitor
Flux Capacitor

Reputation: 1231

Python: replace a decimal number in a string

I have strings like this in a number of files:

 STEP.M                                   0.02540:STEP LENGTH

(notice the space in the first character of the string) In some of the files, there could be additional spaces between some characters:

STEP . M                                   0.02540 : STEP LENGTH

How can I replace the decimal number with another decimal number? i.e. I want this:

STEP.M                                   1.50000:STEP LENGTH

Edit to add: Naturally, the decimal number is not always the same in each file.

Upvotes: 2

Views: 1999

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174874

Think you mean this,

re.sub(r'\d+\.\d+', '1.50000', s)

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49330

This is probably a good time for regular expressions.

>>> import re
>>> s1 =  'STEP.M                                   0.02540:STEP LENGTH'
>>> s2 = 'STEP . M                                   0.02540 : STEP LENGTH'
>>> re.sub(r'\d+\.\d+', '1.50000', s1)
'STEP.M                                   1.50000:STEP LENGTH'
>>> re.sub(r'\d+\.\d+', '1.50000', s2)
'STEP . M                                   1.50000 : STEP LENGTH'

Upvotes: 1

Related Questions