从变量打印原始字符串?(没有得到答案) [英] Print raw string from variable? (not getting the answers)
问题描述
我试图找到一种方法来从变量以原始形式打印字符串.例如,如果我向 Windows 添加一个路径的环境变量,它可能看起来像 'C:\\Windows\Users\alexb\'
,我知道我可以这样做:
I'm trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like 'C:\\Windows\Users\alexb\'
, I know I can do:
print(r'C:\\Windows\Users\alexb\')
但我不能在变量前面放一个 r
.... 例如:
But I cant put an r
in front of a variable.... for instance:
test = 'C:\\Windows\Users\alexb\'
print(rtest)
显然只是尝试打印 rtest
.
我也知道有
test = 'C:\\Windows\Users\alexb\'
print(repr(test))
但这会返回 'C:\\Windows\\Users\x07lexb'
一样
test = 'C:\\Windows\Users\alexb\'
print(test.encode('string-escape'))
所以我想知道是否有任何优雅的方法来制作一个保存该路径的变量打印 RAW,仍然使用测试?如果只是这样就好了
So I'm wondering if there's any elegant way to make a variable holding that path print RAW, still using test? It would be nice if it was just
print(raw(test))
但不是
推荐答案
我遇到了类似的问题并偶然发现了这个问题,感谢 Nick Olson-Harris 的 回答 解决方案在于更改字符串.
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
解决方法有两种:
使用原生 python 函数获取你想要的路径,例如:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory
print(repr(test))
这使它独立于平台,现在可以与 .encode
一起使用.如果这是您的选择,那么它是更优雅的解决方案.
This makes it platform independent and it now works with .encode
. If this is an option for you, it's the more elegant solution.
如果您的字符串不是路径,请以与 python 字符串兼容的方式定义它,在这种情况下通过转义反斜杠:
If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\'
print(repr(test))
这篇关于从变量打印原始字符串?(没有得到答案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!