[Tutor] reading strings
Danny Yoo
dyoo@uclink4.berkeley.edu
Sun, 10 Sep 2000 12:26:28 -0700 (PDT)
> I am new to python (1 day).I have downloaded the python for
> windows platform ver 1.5. Well i was tinkering around with it for
> some time reading the tutorial that came along with it . Well , i
> couldnt figure out 1 thing . How do i input strings in python?
> In other words what is the python equivalent of the followig piece of
> code :-
> print "Whats your name?";#perl code
> $name=<STDIN>;
> chomp($name);
There are two methods that allow easy input, input() and raw_input().
What makes input() different is that it will try to evaluate whatever you
type in. For example:
###
>>> x = input("Please enter a number: ")
Please enter a number: 42
>>> type(x)
<type 'int'>
###
On the other hand, raw_input() will leave what you type untouched --- it
will just be a string.
###
>>> x = raw_input("Please enter a number: ")
Please enter a number: 42
>>> type(x)
<type 'string'>
###
It's very strange, though, that the tutorial doesn't obviously mention
input() or raw_input()! I did a quick scan-through, and nothing stood out
to me either.
Also, you can grab at the stdin filehandle to do input. In Python, this
is exposed as an object with methods such as readline(). The code closest
in spirit to your perl is below:
###
>>> from sys import stdin
>>> line = stdin.readline()
Hello, this is a test.
>>> print line
Hello, this is a test.
# note, there's a trailing '\n' there. We use string.strip to 'chomp'.
>>> from string import strip
>>> print strip(line)
Hello, this is a test.
###