Python 复习笔记(一)

1. 将字符存入文件:
   logfile = open('/tmp/mylog.txt', 'a') # 以追加方式打开/tmp/mylog.txt文件,此时logfile类似于C语言的文件指针
   print >> logfile, 'Fatal error: invalid input!' # 将'Fatal error: invalid input' 存入logfile 中
   cat /tmp/mylog.txt   # 显示/tmp/mylog.txt 内容

2. 将输入的字符赋值给变量:
   name = raw_input('enter your name: ')  # 提示输入字符并赋给name
   print name   # 打印输入的字符

3. 格式输出:
   print 'your name: %s' % (name)
   %s 是个占位符,上面第二个%号是个分隔符,%s 对应()中的内容,如果只有一个占位符,()是可选的,如:
   print 'your name: %s' % "jeff"
   如果是两个或两个以上占位符,()则是必须的,如:
   print 'your name: %s %s' % ("Jeff", "Nie")

4. 字符串是类似于C中的字符串存储的,可以访问下标来访问字符,如:
   pystr = 'Python'
   pystr[0]

5. 访问元组
   atuple = ('robots', 77, 93, 'try')
   atuple[0][2]  # 结果为b
   atuple[1]     # 结果为77

   atuple 元组以C语言角度来看是:{{'robots'}, 77, 93, {'try'}}

posted @ 2011-10-25 18:19  jeff_nie  阅读(286)  评论(0编辑  收藏  举报