问题
I've got to write a single-input module that can convert decimals to Bukiyip (some ancient language with a counting base of 3 or 4). For the purpose of the assignment, we only need to work with base 3.
I've written some code that does this, but it returns my Bukiyip number with quotes, leaving me with an answer such as '110' for 12.
Please help me understand how to work around this? I'm new to Python and keen to learn so explanations will be really appreciated.
def bukiyip_to_decimal(num):
convert_to_string = "012"
if num < 3:
return convert_to_string[num]
else:
return bukiyip_to_decimal(num//3) + convert_to_string[num%3]
I've also tried the following, but get errors.
else:
result = bukiyip_to_decimal(num//3) + convert_to_string[num%3]
print(int(result))
回答1:
You are either echoing the return value in your interpreter, including the result in a container (such as a list, dictionary, set or tuple), or directly producing the repr()
output for your result.
Your function (rightly) returns a string. When echoing in the interpreter or using the repr()
function you are given a debugging-friendly representation, which for strings means Python will format the value in a way you can copy and paste right back into Python to reproduce the value. That means that the quotes are included.
Just print the value itself:
>>> result = bukiyip_to_decimal(12)
>>> result
'110'
>>> print(result)
110
or use it in other output:
>>> print('The Bukiyip representation for 12 is {}'.format(result))
The Bukiyip representation for 12 is 110
回答2:
int()
doesn't work? The quotes are not for decoration, you see. They are part of the string literal representation. "hello"
is a string. It is not hello
with quotes. A bare hello
is an identifier, a name. So you don't wanna strip quotes from a string, which doesn't make any sense. What you want is a int
.
来源:https://stackoverflow.com/questions/36452052/how-to-return-a-string-without-quotes-python-3