Replacing the first space in each line with a comma

I need to perform this operation for every single line in a text file, and then write it to another file. I need to remove the first space and replace it with a comma ( ,).

However, I do not want this to happen with any other spaces on the line. Here is a snippet from the input text file:

Achilles Patroclus
Achilles Triumph of Achilles in Corfu Achilleion
Achilles Antilochus
Achilles Hephaestus
Achilles Shield of Achilles
+4
source share
5 answers

You can do something like this:

[",".join(line.split(" ", 1)) for line in lines]
+6
source

Well, I'm not a python programmer, but I will try to contribute to the solution in terms of regular expressions.

, , whitespace . .

Regex: (^\b\w*\b)(\s)

:

  • g .

  • m .

:

  • (^\b\w*\b) .

  • (\s) . , ?: , (?:\s) .

:

  • \1,. , , whitespace

Regex101 Demo

+2

string replace(old, new, [count]). , .

with open("file-path") as fin, open("new_file_path", "w") as fout:
    for line in fin:
        fout.write(line.replace(' ', ',', 1)
+1

re.sub ^([^\s]*)\s+:

>>> s
'Achilles Triumph of Achilles in Corfu Achilleion'

>>> re.sub(r'^([^\s]*)\s+', r'\1, ', s)
'Achilles, Triumph of Achilles in Corfu Achilleion'
+1

re.sub,

re.sub(" ", ",", x, cnt=1)

xis a string, and cntindicates how much you want to replace

+1
source

All Articles