Use Shortcuts app to format text
You can do this with regex in Shortcuts.

Here with text:


and here with integers:


The code is the same, it’s only the first "Text" action which differ.
More about regex in Shortcuts in this reddit post.

Edit: do not confuse, in the two first "Find Text" in the two screenshots, the | in (\n|$) is the vertical bar character, not a uppercase "i" or a lower case "L".

Edit 2: As asked in the comments by the OP and in the edited question, here is a different version with less constraint in the input (remark: in the first Replace Text action, in the field Replace With, you should read "$1",␣, ie a space should be after the comma, but the screenshot cannot display it, and in the 3rd Replace Text, in the field Find Text, you should read (.+),␣):