python.format未按预期工作

2024-09-27 22:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这对我来说毫无意义。我定义了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)]'

我做错什么了?你知道吗


Tags: 字符串inpytest命令formatfor定义
3条回答

试试这个:(command+"test").format(a,b,c,d,e)也就是说,把它放在括号里。您当前的方法只在"test"上使用格式

只对“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)

为什么不只是

"... >> test".format(a,b,c,d,e)

而不是

"... >> " + "test".format(a,b,c,d,e)

.format只适用于一个string对象,您正在将其应用于"test"。你知道吗

如果你真的想连接两个字符串,首先把它们存储在一个变量中,然后做你需要做的事情。你知道吗

str1 = "example{} " + "test"
str1.format('3')
# example3 test

相关问题 更多 >

    热门问题