0

input (not all the code):

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

output (edited):

[f34\t382\t5.00]
[f35\t42\t3.70]
[f36\t72\t1.09]
[f37\t588\t8.56]
[f38\t2837\t7.82]

Question:

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

2 Answers2

1

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]
Matt Clarke
  • 757
  • 4
  • 15
0

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

pattern = r"\t\S+\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]
The fourth bird
  • 154,723
  • 16
  • 55
  • 70