python .format 未按预期工作

标签 python format

这对我来说毫无意义。我定义了 5 个变量:

a='a'
b='b'
c='c'
d='d'
e='e'

然后我尝试使用这些变量构建命令:

command = "for i in \`python {0}_getSyslogs.py {1} {2} {3}\`\ndo\ngunzip -c {3}/\$i | egrep -i '{4}' >> " .format(a,b,c,d,e)

这按预期工作,结果命令是:

"for i in \\`python a_getSyslogs.py b c d\\`\ndo\ngunzip -c d/\\$i | egrep -i 'e' >> "

令我困惑的是,如果我在字符串中再添加一个组件(即“test”),整个事情就会分崩离析,因为不再进行替换:

command = "for i in \`python {0}_getSyslogs.py {1} {2} {3}\`\ndo\ngunzip -c {3}/\$i | egrep -i '{4}' >> " + "test" .format(a,b,c,d,e)

生成的命令如下:

"for i in \\`python {0}_getSyslogs.py {1} {2} {3}\\`\ndo\ngunzip -c {3}/\\$i | egrep -i '{4}' >> test"

这可能是一个“只见树木不见森林”的问题,但我一直在尝试各种不同的组合,但没有任何效果。

我在 CentOS 上运行 python 2.7.10:

sys.version '2.7.10 (default, Oct 6 2017, 22:29:07) \n[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)]'

我做错了什么?

最佳答案

您仅对“test”字符串应用format 函数。

尝试:

command = "for i in \`python {0}_getSyslogs.py {1} {2} {3}\`\ndo\ngunzip -c {3}/\$i | egrep -i '{4}' >> test" .format(a,b,c,d,e)

关于python .format 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50649316/

相关文章:

Python Asyncio 未使用 asyncio.run_coroutine_threadsafe 运行新协程

python - Flask-SQLAlchemy 无法在线程中更新数据

mysql - 将字符串数据值转换为日期

Excel 互操作 : Formatting Footers

algorithm - 使用 XSLT,如何增加 <xsl :number> (e. g 的 'format' 属性的值。 'a' +1 = 'b')?

java - 开发java(文件)交换格式

python - 如何在 BeautifulSoup 中得到想要的值?

python - Python套接字errno 32损坏的管道

python - 将循环中的数组保存在一个 txt 文件的列中

postgresql - 什么是默认的 PostgreSQL 日志格式