Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使函数将其参数转换为字符串_Python_String_Function_Arguments - Fatal编程技术网

Python 如何使函数将其参数转换为字符串

Python 如何使函数将其参数转换为字符串,python,string,function,arguments,Python,String,Function,Arguments,因此,我试图找出如何使函数将未定义为字符串的字符序列作为输入,并使其自动将其解释为字符串,例如: def printstring(sequence_of_characters): a=str(sequence_of_characters) print(a) 现在当我跑步时: printstring(hello) 我希望终端输出: 'hello' 相反,它输出 Traceback (most recent call last): File "<pyshell#7

因此,我试图找出如何使函数将未定义为字符串的字符序列作为输入,并使其自动将其解释为字符串,例如:

def printstring(sequence_of_characters):
    a=str(sequence_of_characters)
    print(a)
现在当我跑步时:

printstring(hello)
我希望终端输出:

'hello'
相反,它输出

Traceback (most recent call last):
    File "<pyshell#7>", line 1, in <module>
        printstring(hello)
NameError: name 'hello' is not defined
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
打印字符串(你好)
NameError:未定义名称“hello”

现在我意识到我可以在“hello”上调用printstring,但我希望该函数能够接受不是字符串的输入,而仅仅是一个chracter序列。

首先,您应该使用带括号的
printstring(“hello”)
调用它(永远不要忘记它们)

python 100%不可能接受参数并在没有括号的情况下打印它。如果不包含括号,它将把它当作对象或方法

因此,您试图将类指定为字符串

假设你有一门课

class Hello:
    pass
你做不到

Hello = Hello()
它不是那样工作的

def printstring(sequence_of_characters):
    sequence_of_characters=str(sequence_of_characters)
    print(sequence_of_characters)

因为
字符序列
是字符串,您所做的只是重新分配它。

您的问题是,您的
字符序列
必须已经是一个对象或变量
hello
只是一个未赋值的变量。唯一可以像您所希望的那样工作的对象是某种数字类型,如
int
float
long


基本上,
hello
必须是一个等于数字的变量才能工作。没有办法不将其分配给某个对象。

U应该将@Srinath所说的内容称为printstring(“hello”),另外,您可以只
打印(字符序列)
。根据定义,字符序列是一个字符串。名称
hello
不是什么,正如错误消息所示,它是未定义的。基本上,听起来你想知道调用者传递给函数的值的名称(假设有)。仅供参考:
String
不是一个对象。所以没有办法解决这个问题吗?