最佳样例

1。 逐行读取文件:

for line in open('xxx.py'):

     print(line.upper(),end='')

 

2. 蛮特别的字符串索引使用:

     fifth_letter = "MONTY"[4]

     print fifth_letter

    :Y

 

3. print用法:

    3.1通过“+”去合并,及连接字符串和字符串变量

         print "Spam "+"and "+"eggs"

           :Spam and eggs 

         print "The value of pi is around " + str(3.14)    #"+"左右的类型要是字符串

           : The value of pi is around 3.14

   

     3.2通过“%”去合并及连接字符串,字符串变量,或其他数据类型

           string_1 = "Camelot"

           string_2 = "place"

       print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)

           :Let's not go to Camelot. 'Tis a silly place.

       % (string_1, string_2)替代了输出文字里的%s

      3.3 打印或调用时间:

          from datetime import datetime

          now = datetime.now()

          print '%s:%s:%s' % (now.hour, now.minute, now.second)

          : 1:50:40

          print '%s/%s/%s %s:%s:%s a' % (now.month,now.day,now.year,now.hour, now.minute, now.second)

          :5/19/2016 3:33:23 a

 

4. shell下传参给python脚本

   eg: python xxx.py a b

   xxx.py  

import sys
import argparse

args=sys.argv 
ip=args[1]
name=args[2]

 

5. 数据格式的判断:

  5.1 isinstance(arg,type)

    Python 2.7.3 (default, Mar 14 201411:57:14

  [GCC 4.7.2] on linux2
  Type "help""copyright""credits" or "license" for more information.
  >>> astr = "abcdefg"
  >>> alst = list(astr)
  >>> astr
     'abcdefg'
  >>> alst
     ['a''b''c''d''e''f''g']
  >>> isinstance(alst, list)
     True
  >>> isinstance(astr, list)
     False
  >>> isinstance(alst, str)
     False
  >>> isinstance(astr, str)
     True
  >>>

  5.2 type():

   def distance_from_zero(a):

       if type(a) == int or type(a) == float:
           return abs(a)
      else:
          return "Nope"

  

6.循环:

   6.1 正向循环:

         for x in str()/L:

   6.2 反向循环:

         for x in range(-len(a),0,2):

         for x in a[::-2]:

   6.3 间隔循环:

         for x in range(1,len(a),2):

         for x in a[::2]:

   6.4 同时显示值和索引位置:

         for (offset,item) in enumerate(s):

                print(item,'appear in offset',offset)

 

 

 

 



posted on 2016-04-23 15:42  晓风残梦  阅读(201)  评论(0编辑  收藏  举报

导航