regex - python re.sub using() replace string within a line -
I'm trying to simplify: I have a line of text file and I know the exact format. There are six integers in a row different than the spaces.
For example:
line = '78 170 180 1 2 3 '
What should I do with the second number Number This replacement has been passed as a variable (i.e., is not known and not hard-coded):
num_replace_str
Therefore, I want a part of the code like:
newline = re.sub (r '\ d + \ s \ d + \ s \ d + \ s (\ d +) \ s \ d + \ S \ d + \ s', num_replace_str, line)
A result will arise like this:
Print Newline 78 170 180 50 2 3
I Just want to change the fourth number, which I have tried to group (), num_replace_str with string (num_replace_str = '50' in this example.
It seems that you can split the string, enter the new value and " .add.
back together.
< Code> split = Line.split () partition [3] = str (50) new_line = '' .join (division)
example:
& Gt; & Gt; & Gt; Line = '78 170 180 1 2 3 '& gt; & Gt; Split = line split ()> gt; & Gt; Partition [3] = str (50) & gt; New_line = '' .joy (partition) & gt; & Gt; & Gt; Print new_line 78 170 180 50 2 3
It is not that it does not preserve the continuous run of white space. . . If this is an important requirement, then regex can be a better bet.
Comments
Post a Comment