Learn Python The Hard Way - Exercise 6: Strings And Text~

Exercise 6: Strings And Text

Strings also can contain the format characters you’ve discovered so far. You simply put the formatted variables in the
string, and then a % (percent) character, followed by the variable. The only catch is that if you want multiple formats in
your string to print multiple variables, then you need to put them inside ( ) (parenthesis) separated by , (commas).
It’s as if you were telling me to buy you a list of items from the store and you said, “I want milk, eggs, bread, and
soup.” Only as a programmer we can say, “(milk, eggs, bread, soup)” and be done with it.

たまーに、Emacs使っていると画面上の描画に問題が出ることがある、僕の場合は空白の半角スペースあけた時なんかにプロンプトの黒いのがそのまま画面上に残ってたりしたりしてたことが割と頻繁にあった。そのたびにその上をカーソル行き来させて消していたのだけれども、そんなことしなくてもCtrl+Lで再描画をすれば消えると知った。
ReStrucuturedTextの勉強中にEmacsのマニュアルを日本語で書いてるところがあってそこからの情報でした。地道な勉強はやはり役に立つ。

Exercise 7: More Printing
カンマで改行を制御してるのか、でもこれでCheeseとBurgerの間に半角スペースが開くのは不思議だな。

Exercise 8: Printing, Printing
Exercise 9: Printing, Printing, Printing
Exercise 10: What Was That?

1. Go search online to see what other escape sequences are available.

2. Try using ”’ (triple-single-quote) instead. Can you see why you might use that instead of """?

3. Try to combine escape sequences and format strings to create a more complex format.

4. Remember the %r format? Combine %r with double-quote and single-quote escapes and print them out. Compare
%r with %s. Notice how %r prints it the way you’d write it in your file, but %s prints it the way you’d like
to see it?

以下ソース。

tabby_cat = "\tI'm tabbed in.\n"
persian_cat = "I'm split\non a line.\n"
backslash_cat = "I'm \\ a \\ cat.\n"

tab = '\t'

fat_cat = """
I'll do a list:
%s* Cat food
%s* Fishies
%s* Catnip\n\t* Grass
""" % (tab, tab, tab)

cat = tabby_cat + persian_cat + backslash_cat + fat_cat

print cat

print "Test %r %r" % ('\"', '\'')
print "Test %s %s" % ('\"', '\'')

一応Catの集合体だからcatsにしたほうがよかったんだろうか。複数形的に。

Exercise 11: Asking Questions
1. Go online and find out what Python’s raw_input does.

print "Enter Your Name:",                                                           
#name = raw_input()                                                                  
#print "Enter Date and Time with nice format",                                       
#date_time = raw_input()                                                             

#print "Hello %s! Now:%s! Have a nice programming!" % (name, date_time)              

print "How old are you?",
age = raw_input()
print "How many tall are you?",
height = raw_input()
print "How much do you weight?",
weight = raw_input()

print "So, you're %r old, %s tall and %r heavy." % (
    age, height, weight)

Exercise 12: Prompting People

1. In Terminal where you normally run python to run your scripts, type: pydoc raw_input. Read what it
says.
3. Do pydoc for open, file, os, and sys. It’s alright if you don’t understand those, just read through and take notes about interesting things.

Exercise 13: Parameters, Unpacking, Variables

3. Combine raw_input with argv to make a script that does more input from a user.

これちょっとわからないな。どう実現すればいいんだろう。とりあえずぐぐってみてもraw_input argvでぐぐってみてもそれっぽいのないんで、スルーしてみるか。わからないところはスルー推奨みたいに最初に書いてあったし。
一応こんな感じで作ってみたけど、なんか違う感じがする。でもきっとraw_inputのなかで引数は取れないだろうしなぁ。

from sys import argv

script, name = argv
raw_input("Hello " + name + ".\nWhat's up?\n")

print "Have a nice day! %s" % name

Exercise 14: Prompting And Passing
あ、なんか次のエクササイズがやっぱり繋がってたのか。
とりあえず上で僕の意図していたようなものと繋がっていてよかった。

1. Go find out what Zork was, and what Adventure was. See if you can find a copy and play it.
3. Add another argument and use it in your script.

3で今日の日付を書いて、その日付に起こった歴史上の出来事を書いて教えてくれみたいなことやって、Wikipediaでナポレオンについて調べてみたりしてしまった。

Exercise 15: Reading Files

Line 7 we print a little line, but on line 8 we have something very new and exciting. We call a function on txt. You see, what you got back from open is a file and it’s also got commands you can give it. You give a file a command by using the . (dot or period), the name of the command, and and parameters. Just like with open and raw_input. The difference is that when you say txt.read() you’re saying, “Hey txt! Do your read command with no parameters!”

pydocってのがやけに使えるなぁという感じでやっと気づいた。こいつは凄い。

pydoc open
pydoc raw_input
pydoc file

辺りをしておぉとなった。説明はPythonに任せるとしておい。fileをやるとfileってのがオブジェクトだと、そしてreadってのはそこに引っ付いてくるメソッドだとわかる。openってのはファイルを渡すとファイル型のオブジェクトを返すファンクションだとわかる。しかもそれは__builtin__というモジュールに入ってる素敵なファンクションだ。pydoc __builtin__とかpydoc stringとかpydoc mathとかやるとそれぞれモジュールごとのドキュメントが出てくる。うーんマンダム。Python凄い。こりゃ英語圏で人気出るわけだわ。

本気出せやみたいなこと書いてあるので本気出す。

1. Above each line write out in English what that line does.

久々に本気出してみたが、英語があってるかどうかは知らない。というかむちゃくちゃ。

# From sys module(built in) import argv dynamic object.
from sys import argv

# Substitution argments(python ex15.py hogehoge) to two variable:script, filename.
## argments = ex15.py and hogehoge
script, filename = argv

# Use open to open a filename file and substitution it to txt variable(so, Now txt is file object).
## open is __builtin__ module's function 
txt = open(filename)

# Print Sentense and Pass arguments(Now It's filename variable.).
print "Here's your file %r:" % filename
# Print txt(fileobject variable) to using method read within fileobject variable(Now It's txt).
print txt.read()

# Print Sentence
print "I'll also ask you to type it again:"
# Substitute raw_input sentence(User input) to file_again variable.
file_again = raw_input("> ")

# Substitute open(file_again) to txt_again. file_again is user input variable. open is a function to open file and return fileobject. So, designate fileobject substitutes to txt_again.
txt_again = open(file_again)

# Print txt_again fileobject to using method read with no parameter 
print txt_again.read()

3. I used the name “commands” here, but they’re also called “functions” and “methods”. Search around online
to see what other people do to define these.

結構ググって確実なものにした。まぁ、Alan.Gauld先生のところで学んでたのがなかったらかなり難しかっただろうが。あそこのスパルタでもうほとんどPythonが何故オブジェクト指向なのかということぐらいまで理解した。はず。ていうかPythonはじめてAlan.Gauld先生のところでオブジェクトうんたらでJavaオブジェクト指向だよなーPythonは何系の言語なんだろみたいに興味もってみたらそうでしたみたいな。さっき関数型言語みたいなのも読んでみたけど、格好いいなぁ。私は全て状況を支配してみせますよみたいな感じで。実際使ったことないから知らんが。Zed A Shaw先生の忠告を破ってLispやってみたいよLisp

7. Startup python again and use open from the prompt. Notice how you can open files and run read on them right there?

python
txt = open('ex15_sample.txt')
print txt.read()

でおk。

Exercise 16: Reading And Writing Files
一行でまとめろやってやつはこれで。最初はwrite()の中にそのまま入れたけど、一応変数に代入してそれを使った。

s = line1 + "\n" + line2 + "\n" + line3 + "\n"

target.write(s)

Exercise 17: More Files

1. Go read up on Python’s import statement, and start python to try it out. Try importing some things and see if you can get it right. It’s alright if you don’t.

http://effbot.org/zone/import-confusion.htm
http://python.matrix.jp/tips/import.html
http://d.hatena.ne.jp/kakurasan/20090306/p1
この辺を読んだ。かなり時間40分ほどを取った。さらにどのようにモジュールを使えばいいのかおさらいするために、Alan.Gauld先生のLearning to Programで学んだモジュールの辺りまでまた見てみて、mathとかその他もろもろ使ってた時のことを思い出そうと思う。もう前の出来事ですっかり忘れている。

Programming with Modules※フレームの内部のページなので他のコンテントを見たい場合はURLを遡ってください。
http://www.alan-g.me.uk/tutor/tutfunc.htm
ここを読みながらもう一度やっている。

あーそうか、import sysで色々遊んでみたけど、sys.exit()は括弧が必要だけど、sys.versionとかsys.version_infoとかは括弧が必要じゃないのはそれがオブジェクトだからか。大してexitの方は関数だから()が必要。なんだと思う。間違ってたらごめんなさい。
OK.とにかくtime, sys, random, math辺りをインポートしてやりまくった。以前より理解が確実に深まっている。fromとかなんなのかわかったので。math.eの.(ドット)とか何なのかやっとわかったので。
pydocも異常に役立つコマンドで、Pythonの理解のスピードというか、もう本当にPythonとやっていけそうな感じになってきた。