大写方法后发生意外的换行

时间:2017-01-24 07:55:09

标签: python printing newline python-3.6

为什么在\n之后没有print (message_2.capitalize())时,输出会在结果上强制换行?

# Input example python script
# Apparently in python 3.6, inputs can take strings instead of only raw values back in v2.7

message_0 = "good morning!"
message_1 = "please enter something for my input() value:"
message_2 = "the number you entered is ... "
message_3 = "ok, now this time enter value for my raw_input() value:"
message_final1 = "program ended." 
message_final2 = "thank you!"

print ("\n\n")
print (message_0.capitalize() + "\n")
input_num = input(message_1.capitalize())
print ("\n")

# This line is obsoleted in python 3.6. raw_input() is renamed to input() . 
# raw_input_num = raw_input(message_3.capitalize())


# data conversion

print ("Converting input_num() variable to float...\n")
input_num = float(input_num)


print ("\n")
print (message_2.capitalize()) 
print (input_num)


print ("\n")
print (message_final1.capitalize() + " " + message_final2.capitalize())

输出如下:

Good morning!

Please enter something for my input() value:67.3


Converting input_num() variable to float...

The number you entered is ...
67.3


Program ended. Thank you!

3 个答案:

答案 0 :(得分:1)

默认情况下,

print()会添加换行符。所以这两个陈述:

print (message_2.capitalize()) 
print (input_num)

会在消息和号码之间加上换行符。

传入两个对象以打印到一个 print()来电:

print(message_2.capitalize(), input_num)

或告诉print()不要通过将end参数设置为空字符串来添加换行符:

print(message_2.capitalize(), end='')
print(input_num)

答案 1 :(得分:0)

Python print()函数的默认行为是在输入字符串后面打印换行符。

您可以通过添加可选参数end

来更改此行为
print("My message", end="")

答案 2 :(得分:0)

我已经问过我的朋友了,而不是仅仅删除我的问题,我想通过分享答案为这个网站增加价值:

# , operator here removes an unexpected newline. the print statement has a built in newline. That's why! 
print (message_2.capitalize(),(input_num),"\n")

# Alternative way to display the answer
print (message_2.capitalize() + " " + str(input_num))

所以关键是使用逗号操作数或在答案上做一个字符串运算符。