简体   繁体   English

str()在我的函数中不返回字符串

[英]str() not returning string in my function

So I've defined a recursive function numToBaseB that converts a given number in base ten into any other base between 2 and 10. The desired output is a string, but for some reason I keep getting an int. 因此,我定义了一个递归函数numToBaseB,该函数将以10为底的给定数字转换为2到10之间的其他任何底数。所需的输出是字符串,但是由于某种原因,我一直在获取int值。

def numToBaseB(num, b):
    if num == 0:
        return ''
    elif b > 10 or b < 2:
        return "The base has to be between 2 and 10"
    else:
        return numToBaseB(num // b, b ) + str(num % b)

So for me: numToBaseB(4, 2) would return 所以对我来说: numToBaseB(4, 2)将返回

100 100

instead of the desired output: 而不是所需的输出:

'100' '100'

Your program is working as designed: 您的程序按设计工作:

>>> numToBaseB(1024,2)
'10000000000'
>>> numToBaseB(4,2)
'100'

Of course, if you do print(numToBaseB(4,2)) , the quotes will not be displayed. 当然,如果您执行print(numToBaseB(4,2)) ,则不会显示引号。

If you want to have quotes though, you can always do this: 但是,如果您想要引号,则可以始终这样做:

print (" ' "+numToBase(4,2)+" ' ")

But in the program, if you use str() anyways, it will be treated as string ofcourse. 但是在程序中,如果仍然使用str(),它将被视为课程字符串。

:) :)

Edit: typing on phone, so sorry for this madness :( 编辑:在电话上键入,为此感到疯狂:(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM