1、内建函数enumerate
friends = ['john', 'pat', 'gary', 'michael'] for i, name in enumerate(friends): print "iteration {iteration} is {name}".format(iteration=i, name=name)
其中 i 表示:0, 1, 2, 3;
name表示:friends下标为i的内容,即friends[i]
2、print()格式化输出
parents, babies = (1, 1) while babies < 100: print("This generation has %s babies" % (babies)) parents, babies = (babies, parents + babies)
3、函数定义并调用
def greet(name): print("Hello, my name is %s." % name) #print("Hello, my name is %s." % (name)) greet('huabo') greet('yanyan')
4、import模块,字符串匹配
import re for test_string in ['555-1212', 'ILL-EGAL']: if re.match(r'^\d{3}-\d{4}$', test_string): print("%s is a valid UI local phone number" % test_string) else: print("%s rejected" % test_string)
输出:
555-1212 is a valid UI local phone number
ILL-EGAL rejected
5、Dictionaries, generator expressions
prices = {'apple': 0.40, 'banana': 0.50} my_purchase = { 'apple': 1, 'banana': 6} grocery_bill = sum(prices[fruit] * my_purchase[fruit] for fruit in my_purchase) print('I owe the grocer $%.2f' % grocery_bill)
0.4*1+0.5*6 = 3.4
6、 Opening files and output all the content.
#indent your python code to put into an email import glob #out put all the Python files in the current Directory. python_files = glob.glob('*.py') for file_name in sorted(python_files): print(" ------%s" % file_name) with open(file_name) as f: for line in f: print(line.rstrip()) print()
7、时间,条件,输出
from time import localtime activities = {8: 'Sleeping', 9: 'Commuting', 17: 'Working', 18: 'Commuting', 20: 'Eating', 22: 'Resting' } time_now = localtime() print('Current Time: %sYear %sMonth %sDay %sHour %sMin' % (time_now.tm_year, time_now.tm_mon, time_now.tm_mday, time_now.tm_hour, time_now.tm_min)) hour = time_now.tm_hour for activity_time in sorted(activities.keys()): if hour < activity_time: print(activities[activity_time]) break else: print('Unknown, AFK or sleeping!')
8、三单引号字符串
REFRAIN = ''' %d bottles of beer on the wall, %d bottles of beer, take one down, pass it around, %d bottles of beer on the wall! ''' bottles_of_beer = 8 while bottles_of_beer > 1: print(REFRAIN % (bottles_of_beer, bottles_of_beer, bottles_of_beer - 1)) bottles_of_beer -= 1
注意:三单引号字符串可以使得字符串可以换行,很方便。