如何返回不带引号的字符串Python 3 [英] How to return a string without quotes Python 3

查看:820
本文介绍了如何返回不带引号的字符串Python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个单输入模块,该模块可以将小数转换为Bukiyip(某些古老的语言,其基数为3或4).出于分配目的,我们只需要使用基础3.

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.

我已经编写了一些代码来执行此操作,但是它返回带引号的Bukiyip编号,并给我一个答案,例如12的"110".

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.

请帮助我了解如何解决此问题?我是Python的新手,热衷于学习,因此非常感谢您进行解释.

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))

推荐答案

您要么在解释器中回显返回值(包括容器中的结果(例如列表,字典,集合或元组),要么直接生成)您的结果的repr()输出.

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.

您的函数(正确地)返回一个 string .在解释器中回显或使用repr()函数时,会得到一个易于调试的表示形式,对于字符串,这表示Python将以一种格式设置值的格式,您可以将其复制并粘贴回到Python中,重现价值.这意味着包括引号.

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.

只需打印值本身:

>>> 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

这篇关于如何返回不带引号的字符串Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆