How would I replace the text between t and a second t with something

Question:

input (not all the code):

with open(filepath) as f:
    reader = csv.reader(f, delimiter=' ')
    for line in reader:
        print(line)

output (edited):

[f34t382t5.00]
[f35t42t3.70]
[f36t72t1.09]
[f37t588t8.56]
[f38t2837t7.82]

Question:

How would I replace the text between t and the second t with ", "?

Asked By: ApplesAreFruits

||

Answers:

Would something like this work for you?

parts = line.split("t")
result = parts[0] + "," + parts[2]

If you want to keep the tabs then the last line becomes:

result = parts[0] + "t,t" + parts[2]
Answered By: Matt Clarke

You could match 1+ non whitespace chars between 2 tabs, and in the replacement use a comma between 2 tabs.

pattern = r"tS+t"

s = ("[f34  382 5.00]n"
            "[f35   42  3.70]n"
            "[f36   72  1.09]n"
            "[f37   588 8.56]n"
            "[f38   2837    7.82]")

print(re.sub(pattern, "t,t", s))

Output

[f34    ,       5.00]
[f35    ,       3.70]
[f36    ,       1.09]
[f37    ,       8.56]
[f38    ,       7.82]
Answered By: The fourth bird
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.