英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论