I have a text file with 100 lines. On each line, there is a number with format nnn.nn
.
I have another number NNN.NN
. Using Python, I want to replace nnn.nn
on each line with NNN.NN
. But nnn.nn
is located at a different place in the line each time.
I am currently reading in the whole file by:
with open(filename) as f:
my_file = f.readlines()
and I know that I can find the relevant number by doing:
re.findall(r' \d\d\d.\d\d ',my_file[line_index])[0]
but I'm not sure how to tell my code to replace that number (wherever it is) with my new number.
That would be, also with re:
import re
x="23.320 ododkowe 23.565 odef0oi04 30.403 320"
re.sub(r"\d\d.\d\d\d ", "xx.xxx ", x)
output:
'xx.xxx ododkowe xx.xxx odef0oi04 xx.xxx 320'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.