如何防止Python函数解释字符串中的转义字符?

huangapple go评论76阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年4月17日 17:58:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76033891.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定