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
You're getting confused between a string and the representation of a string.
If when you pipe this to bash, you want a
\before the$, just put one there.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 doingprint(x), is no different from writingxto a file.As you can see, even if I dump
valto 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 ifAwas the literal"character,"Ais an unterminated string.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.