python - 在字符串中调用 python 参数

标签 python string

我想在字符串中调用 python 参数。那可能吗? 假设我已将变量 mypath 声明为

mypath = os.path.abspath('1.jpg')

我需要在另一个字符串变量中调用它,如下所示

cmd0 = 'gimp-console-2.8 -b -idf --batch-interpreter python-fu-eval -b "import sys,os;sys.path=[\'.\']+sys.path;import mycode;'
cmd1 = 'mycode.doit('THIS VARIABLE MYPATH SHOULD GO HERE')"'
cmd2 = '-b "pdb.gimp_quit(0)"'
cmdfinal = cmd0 + cmd1 + cmd2
os.system(cmdfinal)

最佳答案

看起来您想要做的是将变量插入字符串的中间。

这是通过字符串格式化完成的。 Python 有几种不同的方法,但最简单的是 str.format 方法,如教程部分 Fancier Output Formatting 中所述:

cmd1 = 'mycode.doit({0})'.format(mypath)

如果 mypath 是字符串 /Users/me/Documents/1.jpg ,那么 cmd1 将是字符串 mycode.doit(/Users/me/Documents/1.jpg)

但这不太正确,因为您正在尝试格式化可以由另一个 Python 解释器运行的命令。因此,您不仅需要字符串的内容,还需要字符串的 Python 文字。你是怎么做到的?

字符串的 repr 是引号中的字符串,经过适当的转义以确保它可以直接在Python代码中使用。 (并非所有对象都如此;例如,有些对象会返回类似 <Spam object at 0x12345678> 的内容,这并不是特别有用;通常仅对于将输出输入 Python 代码有意义的对象才有效,并为您提供完全相同的结果对象。)

那么,你是如何得到它的呢?如 Format String Syntax 中所述,您使用 r 转换说明符:

cmd1 = 'mycode.doit({0!r})'.format(mypath)

现在,cmd 将是字符串 mycode.doit('/Users/me/Documents/1.jpg')

这正是您想要的。

关于python - 在字符串中调用 python 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25880777/

相关文章:

python - salt 执行模块中的产量以在执行期间返回状态

python - 从数据框列的列表中查找字符串值并将字符串值附加为列

java - 用实际值替换环境变量占位符?

string - Bash:重复字符可变次数

c++ - 将 State 的输入转换为缩写

python - python中特定几何图形的二维等值线图

python - Django 过滤符合 ManyToMany 中特定条件的行数

python - Cython 中的 "not a type identifier"错误

c++ - CPP : Parsing String Stream is too slow

python - 如何使 Python 中的类与集合一起运行?