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

时间:2021-12-28 15:38:21

Simple error while inserting variable . Can't seem to figure it out ! meaning and word are of type str .

插入变量时出现简单错误。似乎无法搞清楚!意思和单词是str类型。

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

Error:

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

2 个解决方案

#1


Get rid of the comma

摆脱逗号

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

Or use format

或者使用格式

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

#2


You don't need the comma between the string and the '%'.

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

#1


Get rid of the comma

摆脱逗号

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

Or use format

或者使用格式

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

#2


You don't need the comma between the string and the '%'.

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