我有一个bash命令要运行,并将其分配给变量。 要运行的命令是:
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
我能够在python3中将其打印为:
>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
但是,当我为变量分配相同的值时:
a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
我得到以下信息:
'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''
请注意输出中的\
。
我希望通过变量分配来达到预期的结果(在print
语句中完成)。
答案 0 :(得分:1)
两个字符串完全相同。如果您在IDE上运行这两个命令,或者使用python script.py
print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
print(a)
输出将为
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
只是Python在单引号周围添加了一个额外的反斜杠,因为我们在字符串中也有双引号,并且反斜杠转义了单引号以提供字符串的可打印表示形式
>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
>>> print(a)
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a
'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''
基本上,转义的字符串是字符串的repr
表示形式
从文档中:https://docs.python.org/3/library/functions.html#repr
repr(object)
返回包含对象可打印表示形式的字符串
答案 1 :(得分:1)
看看这个
>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
在这里,您看到\
是因为它在单引号中打印了字符串文字。
>>> a
'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''
如果您打印变量,它将按照您的要求正常显示。
>>> print(a)
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'