Python:函数可以返回字符串吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33479932/
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
Python: can a function return a string?
提问by Rectifier
I am making a recursive function that slices string until it is empty. When it is empty it alternatively selects the characters and is supposed to print or return the value. In this case I am expecting my function to return two words 'Hello' and 'World'. Maybe I have got it all wrong but what I don't understand is that my function doesn't let me print or return string. I am not asking for help but I'd like some explanation :) thanks
我正在制作一个递归函数,它将字符串切片直到它为空。当它为空时,它会交替选择字符并应该打印或返回值。在这种情况下,我希望我的函数返回两个单词“Hello”和“World”。也许我都弄错了,但我不明白的是我的函数不允许我打印或返回字符串。我不是在寻求帮助,但我想要一些解释:) 谢谢
def lsubstr(x):
a= ''
b= ''
if x == '':
return ''
else:
a = a + x[0:]
b = b + x[1:]
lsubstr(x[2:])
#print (a,b)
return a and b
lsubstr('hweolrllod')
so I changed my code to this:
所以我把我的代码改成这样:
def lsubstr(x):
if len(x) <1:
return x
else:
return (lsubstr(x[2:])+str(x[0]),lsubstr(x[2:])+str(x[1]))
lsubstr('hweolrllod')
and what I am trying to make is a tuple which will store 2 pairs of characters and concatenate the next ones,
我想要制作的是一个元组,它将存储 2 对字符并连接下一个字符,
the error I get is TypeError: Can't convert 'tuple' object to str implicitly
我得到的错误是 TypeError: Can't convert 'tuple' object to str 隐式
what exactly is going wrong, I have checked in visualization, it has trouble in concatenating.
到底出了什么问题,我已经检查了可视化,它在连接时遇到了麻烦。
回答by Ethan Bierlein
The and
keyword is a boolean operator, which means it compares two values, and returns one of the values. I think you want to return a tuple instead, like this:
该and
关键字是一个布尔运算符,这意味着它比较两个值,并且返回的值中的一个。我认为您想返回一个元组,如下所示:
...
return (a, b)
And then you can access the values using the indexing operator like this:
然后您可以使用索引运算符访问这些值,如下所示:
a = lsubstr( ... )
a[0]
a[1]
Or:
或者:
word1, word2 = lsubstr( ... )