0
03124123,YOU ARE SITTING IN FRONT OF A COMPUTER LEARNING JAVA.
11231123,YOU ARE STANDING AT THE END OF A ROAD, BEFORE A SMALL BRICK BUILDING. AROUND YOU IS A FOREST. A SMALL STREAM FLOWS OUT OF THE BUILDING AND DOWN A GULLY.
21443132,YOU HAVE WALKED UP A HILL, STILL IN THE FOREST, THE ROAD SLOPES BACK DOWN THE OTHER SIDE OF THE HILL. THERE IS A BUILDING IN THE DISTANCE.
3123,YOU ARE INSIDE A BUILDING, A WELL HOUSE FOR A LARGE SPRING.
42,YOU ARE IN A VALLEY IN THE FOREST, BESIDE A STREAM TUMBLING, ALONG A ROCKY BED.
5,YOU ARE IN OPEN FOREST, WITH A DEE,P VALLEY TO ONE SIDE.
61283,YOU ARE IN OPEN FOREST NEAR BOTH A VALLEY AND A ROAD.

I have this sample lines written in a .txt file. All lines start with a number, followed by a ,.I would like to replace the , coming right after the number with a (space). After conversion, I would have:

03124123 YOU ARE SITTING IN FRONT OF A COMPUTER LEARNING JAVA.
11231123 YOU ARE STANDING AT THE END OF A ROAD, BEFORE A SMALL BRICK BUILDING. AROUND YOU IS A FOREST. A SMALL STREAM FLOWS OUT OF THE BUILDING AND DOWN A GULLY.
21443132 YOU HAVE WALKED UP A HILL, STILL IN THE FOREST, THE ROAD SLOPES BACK DOWN THE OTHER SIDE OF THE HILL. THERE IS A BUILDING IN THE DISTANCE.
3123 YOU ARE INSIDE A BUILDING, A WELL HOUSE FOR A LARGE SPRING.
42 YOU ARE IN A VALLEY IN THE FOREST, BESIDE A STREAM TUMBLING, ALONG A ROCKY BED.
5 YOU ARE IN OPEN FOREST, WITH A DEE,P VALLEY TO ONE SIDE.
61283 YOU ARE IN OPEN FOREST NEAR BOTH A VALLEY AND A ROAD.

I can find the starting position of the matching expression using re.search(".*,", line) where line is any line of the text. How do I replace that , with a (space)?

  • *Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text.* - just as [Amber said](https://stackoverflow.com/a/2763763/3832970) – Wiktor Stribiżew Apr 23 '20 at 20:20
  • @WiktorStribiżew `re.sub(r"([0-9]*,$)", r" ",line)` tried something like this, didn't work out :( –  Apr 23 '20 at 20:25
  • You said `".*,"` worked to find the comma to replace. So, `re.sub(r"(.*),", r"\1 ", line)` is what you should try. – Wiktor Stribiżew Apr 23 '20 at 20:33

0 Answers0