英文:
How to prevent Python function from interpreting escape characters in a string?
问题
The output of the print
function inside func
is some@random
. Is there way to stop a function from converting \100
to @
?
我想要的输出是 'some/100random'
.
英文:
I have a following Python code:
my_str = 'some0random'
def func(x):
print(my_str)
temp_str = repr(x.replace("\\", "/"))
return temp_str
print(func(my_str))
The output of the print
function inside func
is some@random
. Is there way to stop a function from converting \100
to @
?
I know I can use a raw string in variable my_str = r'some\100random'
but the problem is I use this function in our internal program and I don't have access to variable itself. I can only use Python function, which receives a parameter x
from outside of its scope.
The output I want to receive is 'some/100random'
.
答案1
得分: 1
以下是翻译好的部分:
my_str = 'some\100random'
有办法阻止函数将\100转换为@吗?
它不会这样做。
当您执行my_str = 'some\100random'
时,\100
已经被转换为@
。
如果您想在描述的情况下进行此替换,您可以使用以下方法之一:
temp_str = repr(x.replace("@", "/100"))
或者您可以创建一个包含要替换的字符的列表:
TO_BE_REPLACED = '@=$"'
def replace(c):
"""用八进制表示替换字符"""
if c in TO_BE_REPLACED:
return '/%o' % ord(c)
else:
return c
def func(x):
temp_str = repr("".join(replace(i) for i in x))
return temp_str
my_str = 'some\100random'
print(func(my_str))
但这不会恢复字符串的原始定义,所以可能不太有用。
英文:
> my_str = 'some\100random'
> Is there way to stop a function from converting \100 to @?
It does not do so.
When you do my_str = 'some\100random'
, the \100
is already converted to @
.
If you want to do this replacement in the scenario you describe, you can either do
temp_str = repr(x.replace("@", "/100"))
or you can have a list of characters with which you do the replacement:
TO_BE_REPLACED = '@=$"'
def replace(c):
"""Replace a character with its octal representation"""
if c in TO_BE_REPLACED:
return '/%o' % ord(c)
else:
return c
def func(x):
# print(x)
temp_str = repr("".join(replace(i) for i in x))
return temp_str
my_str = 'some0random'
print(func(my_str))
But that will not bring back the original definition of that string, so it is not very useful, probably.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论