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

时间:2016-07-01 22:46:27

标签: python string arcgis

我正在编写一些使用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])

2 个答案:

答案 0 :(得分:0)

根据您的评论,您有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次调用。适当的编码取决于您的特定操作系统和应用程序。 sys.getfilesystemencoding()'utf-8'可能是选择。

答案 1 :(得分:-2)

您可以使用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'>
>>>