【问题标题】:Is there a way to copy my VS Code Snippet string via Pyperclip有没有办法通过 Pyperclip 复制我的 VS Code Snippet 字符串
【发布时间】:2019-09-23 20:09:59
【问题描述】:

我正在尝试获取一个 Python 脚本,该脚本将从我的剪贴板中获取代码并将其格式化为 VS Code sn-p,最后将其放回我的剪贴板(通过 Pyperclip)。

我想逃跑

  • 反斜杠 (\)
  • 引号 (")

我要换

  • 带有 (\t) 的实际选项卡

输入:

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

实际输出: (从剪贴板粘贴)

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

预期输出: (几乎可以立即在 VS Code sn-p 的主体中使用什么方法)

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

我如何获得我缺少的东西,并以某种方式对其进行编码?

【问题讨论】:

    标签: python python-3.x visual-studio-code clipboard pyperclip


    【解决方案1】:

    只需要在字符串引号前加上字母r就可以表示原字符串,避免字符串中的反斜杠转义。像这样:

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

    更多解释请参考官方文档。 String and Bytes literals

    【讨论】:

    • 好的,这只是我的例子。我真的会从剪贴板中取出我的字符串变量。然后我必须对其进行原始编码,即:string.encode('unicode_escape') 你会寻找什么?
    • 只需要在三个引号前加一个字母R就可以了,这是python的内置语法。
    【解决方案2】:

    我已经让它工作了,没有使用布鲁斯的方法....下面是我的代码:

    `

    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)
    

    `

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      相关资源
      最近更新 更多