开发者

Output unformated?

I am newbie in Python. Was doing an exercise in LearnPythonTheHardWay by Mr. Zed Shaw. I have been stuck with this problem

here is the code:

age=input("How old are you?");
height=input("How tall are you?");
weight=input("How much do you weight?");
print ("age = %r height = %r weight = %r" %(age,height,weight))

And its output:

D:\Python>python sample1.py
How old are you?22
How tall are you?182
How much do you weight?178
age = '22\r' height = '1开发者_C百科82\r' weight = '178\r'

I am not understanding, how is that, I am getting "\r" with the output? Please help !!!


It looks like you are using Python 3. In Python 3, the input() function returns a string which is what you typed at the prompt. In Python 2, the input() function returns an evaluated expression, which in your case if you type a number would be an integer.

You have three basic choices:

  • Find a tutorial that uses Python 3
  • Install Python 2 for use with your current tutorial
  • Simulate Python 2 input() by using eval(input(...))


What happens is that on some systems a newline character (the way the language understands that you've hit the enter key) is by the appearance of either \n (more popularly called the newline character) or \r (more popularly called the return character) or both.

Some time in the history of development of various operating systems, some took to \n and some to \r (and some in fact took to using both i.e. \r\n). This is why on some really low-level C programs, you have to check for CR and LF, which, by the way, was inspired by the carriage return and line feed operations on typewriters.

So, what you really need to do is remove both \r and \n (whichever are present) from the end of each line.

However, it may not always be clear which are used, but luckily python gives you a way to deal with that, namely the strip function, which handles all possible combinations of \r and \n.

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜