注意:这是一个假设的问题: 所以我用Google搜索了这个问题的几个变体(“String litel”,“Escape Char”,“Raw String”等),主要是他们所说的解决方案是在字符串的第一个引号之前放置一个“r”。我也尝试将.format()用于原始字符串re / repr,我尝试使用.replace()斜杠,但它已经转换了转义字符。
path = r"C:\Users\Chris\Documents\Python_2.7\2016\MyProgram"
os.path.exists( path ) # Return True
os.listdir( path ) # Returns list of files in directory
但是,如果它是从单独的函数/类返回的预定义变量(例如),该怎么办?
path = Class.Function.GetPath()
os.path.exists( path ) ## Returns False
os.listdir(path) ## Will print something like:
## Windows Error... "C:\\Users\\Chris\\Documents\\Python_2.7\x816\\MyProgram"
所以我的问题是:如何将预定义的变量作为字符串文字,并使这个路径起作用?
更新:这都是假设!只是好奇是否有办法扭转逃脱的角色!!!
示例:
s = "\x77"
print s ## Prints "w"
len(s) ## Returns 1
MagicFunction(s) ## Returns "\x77" ???
答案 0 :(得分:0)
我不太明白你的问题。 Class.Function.GetPath ()
的输出是返回字符串还是原始数据?测试以确保它是一个字符串。如果它不是简单地将返回值强制转换为str
。
path = str(Class.Function.GetPath()) # Make sure the variable is a string
print os.path.exists( path ) # Check the location
print os.listdir(path)
# repr vs str
print path # path is already an str data type.
print repr(path) # Shows the true string value.
如果有换行符,则显示该换行符的唯一方法是通过添加另一个反斜杠来取消该功能,该反斜杠表示为'\\n
而不是' \ n'。
答案 1 :(得分:0)
从问题:
s = "\x77" print s ## Prints "w" len(s) ## Returns 1 MagicFunction(s) ## Returns "\x77" ???
变量s
存储字符串" w"。有几种方法可以编写string literal:
"w"
"\x77"
"\167"
Unicode字符串添加:
"\N{LATIN SMALL LETTER W}"
"\u0077"
"\U00000077"
变量只包含一个字符的字符串" w"。输入文件在输入文件中的写入信息将丢失。因此,MagicFunction
只能在不知道原始格式的情况下返回所有可能形式的列表。