Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing first whitespace in every line with a comma [closed]

Tags:

python

regex

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

However, I don't want this to happen to any other whitespace 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
like image 890
lsch91 Avatar asked Dec 11 '22 18:12

lsch91


2 Answers

You can do something like this:

[",".join(line.split(" ", 1)) for line in lines]
like image 50
user6022341 Avatar answered Jan 05 '23 00:01

user6022341


Using re.sub with ^([^\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'
like image 32
heemayl Avatar answered Jan 05 '23 00:01

heemayl