插入字符串变量时出现Python语法错误

时间:2015-05-07 12:10:12

标签: python

插入变量时出现简单错误。似乎无法解决这个问题! meaningword的类型为str。

rest_command = "display notification \'%s\' with title \'%s\'", %(meaning[0],word[0])
os.system(osascript -e + rest_command)

错误:

File "word-scraper.py", line 20
    rest_command = "display notification \'%s\' with title \'%s\'", %(meaning[0],word[0])
                                                                    ^
SyntaxError: invalid syntax

2 个答案:

答案 0 :(得分:5)

摆脱逗号

>>> "display notification \'%s\' with title \'%s\'" % (meaning[0],word[0])
"display notification 'hello' with title 'foo'"

或使用format

>>> "display notification \'{}\' with title \'{}\'".format(meaning[0],word[0])
"display notification 'hello' with title 'foo'"

答案 1 :(得分:0)

您不需要字符串和'%'之间的逗号。