python escape $ in string and save as variable

85 views Asked by At

I know that it's easy to escape $ in python if you want to print it:

>>> char='$'
>>> print(f'\{char}')
\$

but that's not what I need. I want to save it in a variable; however, i'll always have double backslashes instead of single backslash.

>>> f'\\{char}'
'\\$'
>>> f'\{char}'
'\\$'
>>> f'\\{char}'
'\\$'
>>> repr(f'\{char}')
"'\\\\$'"
>>> repr(f'\\{char}')
"'\\\\$'"

Therefore my_escaped_string = f'\{char}' will be \\$ instead of \$. As this will be used to escape some special characters in a password, which later on will be sent to bash, bash will have real problems with double backslashes.

I've also tried escaped_str = "\" + char, and so on. However, I can't manage to append just a single backslash in from of the escaped character.

Does somebody have enough inspiration to solve it? ChatGPT insists on dumb solutions.

i have my_pass = '1234$5678'and I want to transform it in my_escaped_pass => '1234\\$5678' instead of '1234\\\\$5678'

Later edit: I will do something like that:

command=f"echo {password} | sudo passwd monitoringuser --stdin"
ssh.execute_command(command)

At the moment I execute the command, if the password is 1234$5678 or 1234\\$5678 it's bad. It has to be 1234\$5678

1

There are 1 answers

5
blueteeth On

You're getting confused between a string and the representation of a string.

❯ s = "\$"

❯ print(s)
\$

❯ s
'\\$'

If when you pipe this to bash, you want a \ before the $, just put one there.

i ❯ my_pass = "abcdef"

i ❯ val = f'{my_pass[:3]}\${my_pass[3:]}'

i ❯ print(val)
abc\$def

i ❯ val
'abc\\$def'

In response to the comment...

I don't think you're right about this. When you run print(), you are effectively writing to a file called /dev/stdout (on Mac and Linux), so doing print(x), is no different from writing x to a file.

i ❯ with open("foo", "w") as f:
...     f.write(val)
...

i ❯ cat foo
abc\$def

As you can see, even if I dump val to a file, it doesn't have two slashes.

In the repr, \\ means a literal slash.

Here are some other options which might shed more light:

Escaping string termination

\" is a single character and it means the literal " character. Imaging if A was the literal " character, "A is an unterminated string.

i ❯ "\"
  Input In [32]
    "\"
    ^
SyntaxError: unterminated string literal (detected at line 1)

Literal \

As \ usually means "escape the next character", if the next character is usually escapable AND we actually want a \ character, we have to indicate that we literally want that character, and not for it to perform its usual job.

So \\ is a single \ character. The repr shows its escaped state, but if we print it, we see it's just a single character.

i ❯ "\\"
'\\'
i ❯ print("\\")
\