换行字符在Python中的返回字符串中无效。

huangapple go评论49阅读模式
英文:

New line character does not work in a return string in Python

问题

在下面的代码中,我尝试在一个函数中进行计算,然后将所有的值以字符串的形式返回给Python主程序体。问题在于在返回语句中使用的换行符 \n 不起作用。这是为什么呢?

# 创建函数
def program(value):
    # 创建变量
    tip_percentage = 10
    tip_amount = 0
    final_bill = 0

    # 计算
    tip_amount = value * tip_percentage / 100
    final_bill = value + tip_amount

    # 打印输出
    x = ("value -> \n", value, " Tip -> \n", tip_amount, "Total value -> \n", final_bill)
    print(x)
    return x

# 主程序体
value = int(input("Enter value : "))
value = program(value)
print(value)

尝试从函数中返回一个值。然后在返回语句中,\n 换行字符不起作用。

英文:

Here in the below code, I try to do a calculation in a function and then I return all the values in a string to the main program body in Python. The issue here is the new line character \n does not work with my code in the return statement.
What is the reason for that?

#create function
def program(value):
    #creat variables
   
    tip_percentage=10
    tip_amount=0
    final_bill=0

    #calculations
    tip_amount=value*tip_percentage/100
    final_bill=value+tip_amount

    #print output  
    x=("value -> \n",value," Tip -> \n",tip_amount,"Total value -> \n",final_bill)
    print(x)
    return x

#Main body
value=int(input("Enter value : "))
value=program(value)
print(value)

Tried returning a value from a function. Then in the return statement the \n which is the new line character does not work.

答案1

得分: 2

The Tuple object you return x=("value -> \n", value, " Tip -> \n", tip_amount, "Total value -> \n", final_bill) doesn't interpret escape sequences like \n; it treats them as normal strings.

You can return a string instead.

x = "value -> \n{}\nTip -> \n{}\nTotal value -> \n{}".format(value, tip_amount, final_bill)

英文:

The Tuple object you return x=("value -> \n",value," Tip -> \n",tip_amount,"Total value -> \n",final_bill) doesn't not interpret escape sequences like \n it deal with it as normal string.

You can return a string instead.

x= "value -> \n{}\nTip -> \n{}\nTotal value -> \n{}".format(value, tip_amount, final_bill) 

答案2

得分: 1

x=("value -> \n", value, "Tip -> \n", tip_amount, "Total value -> \n", final_bill)

在上面的行中,你将字符串写成了一个元组。你需要将它转换为一个字符串。

英文:
x=("value -> \n",value," Tip -> \n",tip_amount,"Total value -> \n",final_bill) 

In the above line, you are writing your string as a tuple. You have to convert it to a string.

huangapple
  • 本文由 发表于 2023年2月16日 05:59:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定