如何将字符串转换为 python 中的字符串文字?

How do I convert a string to a string literal in python?

我正在编写一些使用 Onclick 事件获取文件路径的代码。我需要确保这些文件路径是文字,以确保它们是正确的,这样我的其余代码就可以 运行。现在我想我得到的文件路径是 unicode。基本上我需要这个:

u"File\location\extra\slash"

变成这样:

r"File\location\extra\slash"

我该怎么做?我一直没能找到真正能够成功做到这一点的人,而且文档中也没有这方面的任何示例。我无法更改为我提供文件路径 Onclick 事件的函数的工作方式。

这里是有问题的代码:

class SetLayer(object):
    """Implementation for leetScripts_addin.button2 (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
    def onClick(self):
        self.a = pythonaddins.GetSelectedCatalogWindowPath()
        print self.a
        #code split up path here
        self.b = os.path.split(str(self.a))
        self.c = self.b[0]
        self.d = os.path.split(self.c)
        self.e = (self.b[1])
        self.f = (self.d[1])
        self.g = (self.d[0])

您可以使用 eval。

MacBookPro:~ DavidLai$ python
Python 2.7.11 (default, Jan 22 2016, 08:29:18)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = u"File\location\extra\slash"
>>> y = eval("r\"" + x + "\"")
>>> y
'File\location\extra\slash'
>>> type(y)
<type 'str'>
>>>

从您的评论中,您有 a = u'File\location\extra\slash',您想要提取 e = 'slash'f = 'extra'g = 'File\location'。这里不需要将字符串转换为字符串文字;您刚刚对各种级别的字符串转义感到非常困惑。

您需要决定 efg 应该是 Unicode 字符串还是字节串。 Unicode 字符串可能是正确的选择,但我无法为您做出这样的选择。无论您选择什么,您都需要确保始终知道您是在处理 Unicode 字符串还是字节串。目前,a 是一个 Unicode 字符串。

如果您想要 efg 的 Unicode 字符串,您可以执行

self.e, temp = os.path.split(self.a)
self.g, self.f = os.path.split(temp)

如果您需要字节串,您需要使用适当的编码对 self.a 进行编码,然后执行上述 os.path.split 调用。什么是合适的编码将取决于您的具体 OS 和应用程序。 sys.getfilesystemencoding()'utf-8' 是可能的选择。