字符串上的 Python 语法无效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34970049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:47:53  来源:igfitidea点击:

Python invalid syntax on a string?

pythonpython-2.7syntax

提问by A.J.

I am very new to coding so I hope my question makes sense/is formatted correctly.

我对编码很陌生,所以我希望我的问题有意义/格式正确。

Here is my code:

这是我的代码:

#this function takes a name and a town, and returns it as the following:
#"Hello. My name is [name]. I love the weather in [town name]." 

def introduction("name","town"):
    phrase1='Hello. My name is '
    phrase2='I love the weather in '
    return ("phrase1" + "name" + "phrase2" + "town") 

E.g. introduction("George","Washington")in the python shell would return as "Hello. My name is George. I love the weather in Washington."

例如introduction("George","Washington")在 python shell 中将返回为"Hello. My name is George. I love the weather in Washington."

My problem is that my code is not doing that. Instead I get the following error:

我的问题是我的代码没有这样做。相反,我收到以下错误:

Invalid syntax: <string> on line 1". In Wing101 **,"town"): 

has a red swiggle under it. I'm not sure what I did wrong...I know "name" and "town" are strings and not variables, but I really have no idea how to fix it.

在它下面有一个红色的摆动。我不确定我做错了什么......我知道“name”和“town”是字符串而不是变量,但我真的不知道如何解决它。

Any help/comments are appreciated.

任何帮助/评论表示赞赏。

采纳答案by Martijn Pieters

You can't use string literals as function arguments, no. You can only use variable names. Remove all the double quotes:

您不能使用字符串文字作为函数参数,不。您只能使用变量名。删除所有双引号:

def introduction(name, town):
    phrase1='Hello. My name is '
    phrase2='. I love the weather in '
    return (phrase1 + name + phrase2 + town) 

You pass in strings when calling the function:

调用函数时传入字符串:

introduction("George", "Washington") 

and these then get assigned to nameand townrespectively.

然后这些分别分配给nametown