0

I'm trying to get a Python script that will take code from my clipboard and format it to be a VS Code snippet, finally place it back on my clipboard (via Pyperclip).

I want to escape

  • Backslashes (\)
  • Quotes (")

I want to replace

  • Actual tabs with (\t)

Input:

import pyperclip
string = """def print_string():
    print("YOLO\n")
"""
x = string.replace("\\", "\\\\").replace("\"","\\\"").replace("\t","\\t")
pyperclip.copy(x)

Actual Output: (Pasting from the clipboard)

def print_string():
    print(\"YOLO
\")

Expected Output: (What would be ok to almost immediately be used in the body of a VS Code snippet)

def print_string():
\tprint(\"YOLO\\n\")

How do I get what I'm missing, encoding it a certain way?

ben.weller
  • 33
  • 6

2 Answers2

0

You just need to precede the string quotation marks with the letter r to represent the original string and avoid backslash escaping in the string. Like this:

string = r"""def print_string():
    print("YOLO\n")
"""

For more explanations, please refer to the official documentation. String and Bytes literals

bruce
  • 462
  • 6
  • 9
  • Ok so this was just my example. I will really be getting my string variable out of my clipboard. I would have to raw encode it then, is: ```string.encode('unicode_escape')``` What you would be looking for to do that? – ben.weller Sep 26 '19 at 14:25
  • You just need to add the letter R before the three quotation marks, then it works, it's a built-in syntax of python. – bruce Sep 27 '19 at 05:57
0

I've gotten it working, not using Bruce's method....below is my code:

`

import pyperclip
string = pyperclip.paste()
my_list = []
for x in string.split("\r\n"):
    my_string = x.replace("\\", "\\\\").replace("\"","\\\"").replace("\t","\\t").replace("    ", "\\t")
    my_list.append(f"\"{my_string}\",")
value = "\n".join(my_list)
pyperclip.copy(value)

`

ben.weller
  • 33
  • 6