[英]Python and terminal - Strings with special characters
I know the Python thing that if I'm using interactive interpreter and I write '\\\\ '
it prints '\\\\ '
but if if I write print '\\\\ '
it prints '\\ '
. 我知道Python的事情,如果我使用交互式解释器并且我写
'\\\\ '
它打印'\\\\ '
但是如果我写print '\\\\ '
它打印'\\ '
。
What I'm trying to do is (in a script called p.py
): 我正在尝试做的是(在一个名为
p.py
的脚本中):
import os
os.system('echo ' + 'string with spaces'.replace(' ', '\ '))
obviously it won't let me do this. 显然它不会让我这样做。 I mean, Python manages to add TWO backslashes instead of one but I think it does so only in interactive mode, but the terminal, when passed special chars like
\\
, ignores them. 我的意思是,Python设法添加两个反斜杠而不是一个,但我认为它只在交互模式下这样做,但终端,当通过像
\\
特殊字符时,忽略它们。
So that, as the output of the provious code, I get: 所以,作为这些条款的输出,我得到:
local:$ string with spaces
and not 并不是
local:$ string\ with\ spaces
I already tried hardcoded strings and everything else in Python, but I guess the problem is with shell strings. 我已经在Python中尝试过硬编码字符串和其他所有内容,但我想问题是shell字符串。
How could I solve this? 我该怎么解决这个问题?
It it can help to find alteratives solutions, what I'm trying to do is moving a file from python with the mv
command, and this file has spaces in its name. 它可以帮助找到替代解决方案,我正在尝试做的是使用
mv
命令从python移动文件,并且此文件的名称中包含空格。
os.system('echo ' + 'string with spaces'.replace(' ', '\ '))
In that line, the last string '\\ '
will try to escape a space, even though that is not an escape sequence. 在该行中,最后一个字符串
'\\ '
将尝试转义空格,即使这不是转义序列。 If you want it to become a space with a preceding backspace, you can either escape the backspace ( '\\\\ '
), or you can use a raw string which will ignore all escape sequences ( r'\\ '
). 如果您希望它成为具有前置退格的空格,您可以转义退格(
'\\\\ '
),也可以使用原始字符串忽略所有转义序列( r'\\ '
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.