標準入力から文字列を受け取る

じゃあ次は標準入力から文字列を受け取るプログラム。受け取った後表示するだけでは芸がないので、文字列の長さもついでに返すようにしてみる。空白を受け取った場合は終了と判断する。

stdinput.py

while(1):
s = raw_input()
if s == '':
break
print 'What you have just typed is \'%s\'' % (s)
print 'The length of the string is %d' % (len(s))

実行結果。

C:\Python24>python.exe stdinput.py
hatena
What you have just typed is 'hatena'
The length of the string is 6
What is your name?
What you have just typed is 'What is your name?'
The length of the string is 18

これは色々拡張して遊べそうだ。