Python 从变量打印原始字符串?(没有得到答案)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18707338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print raw string from variable? (not getting the answers)
提问by aescript
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:
我试图找到一种方法来从变量以原始形式打印字符串。例如,如果我向 Windows 添加一个路径的环境变量,它可能看起来像'C:\\Windows\Users\alexb\'
,我知道我可以这样做:
print(r'C:\Windows\Users\alexb\')
But I cant put an r
in front of a variable.... for instance:
但我不能把r
一个变量放在前面......例如:
test = 'C:\Windows\Users\alexb\'
print(rtest)
Clearly would just try to print rtest
.
显然只是尝试打印rtest
。
I also know there's
我也知道有
test = 'C:\Windows\Users\alexb\'
print(repr(test))
But this returns 'C:\\Windows\\Users\x07lexb'
as does
但这种回报'C:\\Windows\\Users\x07lexb'
一样
test = 'C:\Windows\Users\alexb\'
print(test.encode('string-escape'))
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
所以我想知道是否有任何优雅的方法来制作一个保存该路径打印 RAW 的变量,仍然使用测试?如果只是这样就好了
print(raw(test))
But its not
但它不是
采纳答案by OlavRG
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answerthat the solution lies with changing the string.
我遇到了类似的问题并偶然发现了这个问题,感谢 Nick Olson-Harris 的回答,解决方案在于改变字符串。
Two ways of solving it:
两种解决方法:
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))
This makes it platform independent and it now works with
.encode
. If this is an option for you, it's the more elegant solution.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))
使用本机 python 函数获取您想要的路径,例如:
test = os.getcwd() # In case the path in question is your current directory print(repr(test))
这使得它独立于平台,现在可以与
.encode
. 如果这是您的选择,那么它是更优雅的解决方案。如果您的字符串不是路径,请以与 python 字符串兼容的方式定义它,在这种情况下,通过转义反斜杠:
test = 'C:\Windows\Users\alexb\' print(repr(test))
回答by Nick Olson-Harris
You can't turn an existing string "raw". The r
prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n
, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10)
, by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.
您无法将现有字符串变为“原始”。解析器r
可以理解字面量的前缀;它告诉它忽略字符串中的转义序列。但是,一旦解析了字符串文字,原始字符串和“常规”字符串之间就没有区别。例如,如果您有一个包含换行符的字符串,则无法在运行时判断该换行符是否来自转义序列、来自三引号字符串中的文字换行符(甚至可能是原始字符串!)、来自调用,通过从文件中读取它,或者您可能想出的任何其他内容。从这些方法中的任何一个构造的实际字符串对象看起来都一样。\n
chr(10)
回答by DrawT
Get rid of the escape characters before storing or manipulating the raw string:
在存储或操作原始字符串之前去掉转义字符:
You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:
您可以将路径“\”的任何反斜杠更改为正斜杠“/”,然后再将它们存储在变量中。正斜杠不需要转义:
>>> mypath = os.getcwd().replace('\','/')
>>> os.path.exists(mypath)
True
>>>
回答by Bryant Sullivan
Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.
由于 \" 末尾的转义字符,您的特定字符串将无法按输入方式工作,不允许它在引号中关闭。
Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.
也许我只是错了,因为我对 python 还是很陌生,所以如果是这样,请纠正我,但是,稍微改变它以进行调整,repr() 函数将完成复制存储在一个字符串中的任何字符串的工作变量作为原始字符串。
You can do it two ways:
你可以通过两种方式做到这一点:
>>>print("C:\Windows\Users\alexb\")
C:\Windows\Users\alexb\
>>>print(r"C:\Windows\Users\alexb\")
C:\Windows\Users\alexb\
Store it in a variable:
将其存储在一个变量中:
test = "C:\Windows\Users\alexb\"
Use repr():
使用 repr():
>>>print(repr(test))
'C:\Windows\Users\alexb\'
or string replacement with %r
或用 %r 替换字符串
print("%r" %test)
'C:\Windows\Users\alexb\'
The string will be reproduced with single quotes though so you would need to strip those off afterwards.
该字符串将使用单引号复制,因此您需要在之后将其去掉。
回答by Samer Alkhabbaz
In general, to make a raw string out of a string variable, I use this:
通常,要从字符串变量中生成原始字符串,我使用以下命令:
string = "C:\Windows\Users\alexb"
raw_string = r"{}".format(string)
output:
输出:
'C:\\Windows\Users\alexb'
回答by Jimmynoarms
I know i'm too late for the answer but for people reading this I found a much easier way for doing it
我知道我的答案为时已晚,但对于阅读本文的人来说,我找到了一种更简单的方法
myVariable = 'This string is supposed to be raw \'
print(r'%s' %myVariable)
回答by An Khang
Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:
只需简单地使用 r'string'。希望这会对您有所帮助,因为我看到您还没有得到预期的答案:
test = 'C:\Windows\Users\alexb\'
rawtest = r'%s' %test
回答by Nick Po
I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com. But when I print it in the interactive mode I get double slash - '\\w' as @Jimmynoarms said:
我将我的变量分配给大型复杂模式字符串以与 re 模块一起使用,并且它与其他几个字符串连接在一起,最后我想打印它,然后在 regex101.com 上复制和检查。但是当我在交互模式下打印它时,我得到了双斜杠 - '\\w' 正如@Jimmynoarms 所说:
The Solution for python 3x:
python 3x的解决方案:
print(r'%s' % your_variable_pattern_str)
回答by Dhananjay_Goratela
Replace back-slash with forward-slash using one of the below:
使用以下方法之一将反斜杠替换为正斜杠:
- re.sub(r"\", "/", x)
- re.sub(r"\", "/", x)
- re.sub(r"\", "/", x)
- re.sub(r"\", "/", x)
回答by kakka
i wrote a small function.. but works for me
我写了一个小函数..但对我有用
def conv(strng):
k=strng
k=k.replace('\a','\a')
k=k.replace('\b','\b')
k=k.replace('\f','\f')
k=k.replace('\n','\n')
k=k.replace('\r','\r')
k=k.replace('\t','\t')
k=k.replace('\v','\v')
return k