[英]How do I make it so the updated value of a string stays, after the function has completed its job?
[英]How do I make a function convert its argument to a string
因此,我试图弄清楚如何使函数将未定义为字符串的字符序列作为输入,并使其自动将其解释为例如字符串:
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
现在,我意识到可以在“ hello”上调用printstring了,但是我希望函数能够接受已经不是字符串,而只是一系列字符的输入。
首先,您应该使用带括号的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)
因为sequence_of_characters
是字符串,而您正在做的就是重新分配它。
您的问题是您的sequence_of_characters
必须已经是一个对象或变量。 hello
只是一个未分配的变量。 唯一可以像您想要的那样工作的对象将是某种数字类型,例如int
或float
或long
。
基本上, hello
必须是一个等于数字的变量才能起作用。 没有办法不将其分配给某些对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.