0

So, I'm trying to write this code that gets its input from the clipboard and then transforms the input by adding apostrophe and comma to the start and end of each line. This is the code I've written.

import pyperclip
text=pyperclip.paste()

# Separate lines and add stars.
lines = text.split('\n')
for i in range(len(lines)): # loop through all indexes in the "lines" list:
    lines[i]="'" + lines[i] + "'," # add apostrophe to each string in "lines" list
text='\n'.join(lines)
pyperclip.copy(text)

However, the problem with this code is that the apostrophe at the end of each line displays on a new line instead of on the same line. This is the result I get:
what i got

But this is what i wanna get:
What I wanna get

So, basically I want the apostrophe and comma at the end of each line to appear at the end of each line not on a new line.

Matiiss
  • 5,970
  • 2
  • 12
  • 29
Joseph
  • 1

1 Answers1

0

If using regex is okay, you can use it to replace every newline character with 'newlinechar' and just add ' at the start and end of your text. (matching new line was taken from this answer)

import re

text = "asd\n123\nslfdgj"

text = re.sub(r"(\r\n|\r|\n)", "'\n'", text)
text = f"'{text}'"
print(text)

This example produces:

'asd'
'123'
'slfdgj'
Grekkq
  • 679
  • 6
  • 14