x=4
y=5
z=x+y
print("Four equals %d"%z)
print("the result is {0:d}".format(z))
# 花括号表示占位,:用来间隔传入的值和它的格式
# d表示以整数形式显示这个数字
a=[1,2,3,4]
b=["first","second","third","fourth"]
c=a+b
print("{0}, {1}, {2}".format(a, b, c))
print ("{0:.3f}".format(8.3/2.7))
print("{0:.1f}".format(8.3/2.7))
print(type(c))
#可以对所有对象调用这个函数,来获得关于 Python如何处理这个对象的更多信息
print("{0:s}".format('I\'m enjoying learning Python.'))
#在字符串中的符号和语法符号会混淆的情况下,可以使用转义符/
print("{0:s}".format("This is a long string. Without the backslash \
it would run off of the page on the right in the text editor and be very \
difficult to read and edit. By using the backslash you can split the long \
string into smaller strings on separate lines so that the whole string is easy \
to view in the text editor."))
#长字符串分成多行,\必须位于每一行的最后一位,但是这种在结果页并没有分行处理
print("{0:s}".format('''You can use triple single quotes
for multi-line comment strings.'''))
print("{0:s}".format("""You can also use triple double quotes
for multi-line comment strings."""))
#可以直接对结果和命令的字符串进行分行处理
string1 = "This is a "
string2 = "short string."
sentence = string1 + string2
print("{0:s}".format(sentence))
print("{0:s} {1:s}{2:s}".format("She is", "very "*4, "beautiful."))
m = len(sentence)
print("{0:d}".format(m))
string1 = "My deliverable is due in May"
string1_list1 = string1.split()
#split的后面没有参数,默认分割符号为空格
string1_list2 = string1.split(" ",2)
#设定拆除符号位空格,同时设定了拆除的空格个数为2,即把字符串拆分为三个单独的字符串
print("{0}".format(string1_list1))
print("FIRST PIECE:{0} SECOND PIECE:{1} THIRD PIECE:{2}"\
.format(string1_list2[0], string1_list2[1], string1_list2[2]))
string2="Your,deliverable,is,due,in,June"
string2_list=string2.split(',')
print(string2_list)
print("{0} {1} {2}".format(string2_list[1], string2_list[5],\
string2_list[-1]))
使用 join 函数将列表中的子字符串组合成一个字符串。join 函数 将一个参数放在 join 前面,表示使用这个字符(或字符串)在子字符串之间进行组合
print("{0}".format(','.join string2_list ))
在这个示例中,附加参数为一个逗号,位于圆括号中。所以 join 函数将子字符串组合成一 个字符串,子字符串之间为逗号。因为列表中有 6 个子字符串,所以子字符串被组合成一个 字符串,子字符串之间有 5 个逗号。新生成的字符串是 Your,deliverable,is,due,in,June
使用 strip、lstrip 和 rstrip 函数从字符串两端删除不想要的字 符。这 3 个函数都可以在括号中使用一个附加参数来设定要从字符串两端删除的字符(或 字符串)
#一种删除方法
string3 = " Remove unwanted characters from this string.\t\t \n"
print("{0:s}".format(string3))
string3_lstrip=string3.lstrip()
#从左侧删除,删除了左边的空格
print ("lstrip:{0:s}".format(string3_lstrip))
string3_rstrip=string3.rstrip()
#从右侧删除,删除了转表符和转行符
print ("rstrip:{0:s}".format(string3_rstrip))
string3_strip=string3.strip()
#从两侧删除
print ("strip:{0:s}".format(string3_strip))
#另一种删除方法
string4 = "$$The unwanted characters have been removed.__---++"
string4_strip = string4.strip('$_-+')
#将这些想要删除的符号作为附加参数就能删除
print("{0:s}".format(string4_strip))
string5 = "Let's replace the spaces in this sentence with other characters."
string5_replace = string5.replace(" ", "!@!")
#将string5中的空格键替换为!@!
print("Output #32 (with !@!): {0:s}".format(string5_replace))
lower 和 upper 函数分别 用来将字符串中的字母转换为小写和大写。capitalize 函数对字符串中的第一个字母应用upper 函数,对其余的字母应用 lower 函数
string6 = "Here's WHAT Happens WHEN You Use lower."
print("{}".format(string6.lower()))
string7 = "Here's what Happens when You Use UPPER."
print("Output #35: {0:s}".format(string7.upper()))
string5 = "here's WHAT Happens WHEN you use Capitalize."
print("Output #36: {0:s}".format(string5.capitalize()))
#对字符串中每一个单词的首字母都进行首字母大写
string5_list = string5.split()
for word in string5_list:
print("{0:s}".format(word.capitalize()))
import re
通过导入 re 模块,你可以使用一大波函数和元字符来创建和搜索任意复杂的模式。
元字符(metacharacter)是正则表达式中具有特殊意义的字符。每个元字符都有特殊意义,它们使正则表达式能够匹配特定的字符串。常用的元字符包括 |、()、[]、.、*、+、?、^、 $ 和 (?P)
re 模块中还包括很多有用的函数,用于创建和搜索特定的模式
import re
# 计算字符串中模式出现的次数
string = "The quick brown fox jumps over the lazy dog."
string_list = string.split()
pattern = re.compile(r"The", re.I)
#re.compile 函数将文本形式的模式编译成为编译后的正则表达式
#re.I 函数确保模式是不区分大小写的,能同时在字符串中匹配“The”和“the”
#原始字 符串标志 r 可以确保 Python 不处理字符串中的转义字符,比如 \、\t 或 \n。这样在进行模式匹配时,字符串中的转义字符和正则表达式中的元字符就不会有意外的冲突。
count = 0
for word in string_list:
if pattern.search(word):
# re.search 函数将列表中的每个单词与正则表 达式进行比较
count += 1
print("{0:d}".format(count))
如果想在屏幕上打印出每个匹配的字符串, 而不是匹配的次数
string = "The quick brown fox jumps over the lazy dog."
string_list = string.split()
pattern = re.compile(r"(?PThe)" , re.I)#
# (?P)是一个出现在 re.compile 函数中的元字符
#这个元字符使匹配的字符串可以在后面的程序中通过组名符号 来引用。在这个示例中,这个组被称为 。
for word in string_list:
if pattern.search(word):
print("{:s}".format(pattern.search(word).group('match_word')))
re.sub 函数来在文本中用一种模式替换另一种模式
# 使用字母“a”替换字符串中的单词“the”
string = "The quick brown fox jumps over the lazy dog."
string_to_find = r"The"
pattern = re.compile(string_to_find, re.I)
print("{:s}".format(pattern.sub("a", string)))
Python 中包含了 datetime 模块,它提供了非常强大的功能来处理日期和时间。
from datetime import date, time, datetime, timedelta
from datetime import date, time, datetime, timedelta
#date函数中生成的时间只有年月日,没有具体时间
today = date.today()
print("today: {0!s}".format(today))
print("{0!s}".format(today.year))
print("{0!s}".format(today.month))
print("{0!s}".format(today.day))
#datetime生成的时间既有年月日,也有具体时间
current_datetime = datetime.today()
print("{0!s}".format(current_datetime))
可以运用timedelta函数对时间进行运算
#生成变量,变量值为需要增加活着减少的时间
one_day = timedelta(days=-1)
#表示一天前
one_week = timedelta(weeks=+1)
#表示一周后
yesterday = today + one_day
next_week = today + one_week
print("yesterday: {0!s}".format(yesterday))
print("last_week: {0!s}".format(next_week))
eight_hours = timedelta(hours=-8)
print("{0!s} {1!s}".format(eight_hours.days, eight_hours.seconds))
# output:-1 57600
#规范化:hours=-8 的输出是 (-1 days, 57,600 seconds),不是更简单的 (-28,800 seconds)
#86 400 秒(3600 秒每小时 *24 小时每天)-28 800 秒(3600 秒每小时 *8 小时)= 57 600 秒。
对date产生的时间进行加减运算之后可以得到具体时间(包含时分秒)
date_diff = today - yesterday
print("{0!s}".format(date_diff))
print("{0!s}".format(str(date_diff).split()))
#在split之后,可以发现由三个要素构成—— 1 days, 0:00:00——['1', 'days,', '0:00:00']
根据一个 date 对象来创建具有特定格式的字符串
print("{:s}".format(today.strftime('%m/%d/%Y')))
print("{:s}".format(today.strftime('%b %d, %Y')))
print("{:s}".format(today.strftime('%Y-%m-%d')))
print("{:s}".format(today.strftime('%B %d, %Y')))
#Output : 11/17/2019
#Output : Nov 17, 2019
#Output : 2019-11-17
#Output : November 17, 2019
# 根据一个表示日期的字符串
# 创建一个带有特殊格式的datetime对象
date1 = today.strftime('%m/%d/%Y')
date2 = today.strftime('%b %d, %Y')
date3 = today.strftime('%Y-%m-%d')
date4 = today.strftime('%B %d, %Y')
# 基于4个具有不同日期格式的字符串
# 创建2个datetime对象和2个date对象
print("{!s}".format(datetime.strptime(date1, '%m/%d/%Y')))
print("{!s}".format(datetime.strptime(date2, '%b %d, %Y')))
#date1、2是一个字符串变量,要将它变成datetime形式
#先使用strptime进行处理,注意括号里的格式要和date1、2本身的格式相同
# 仅显示日期部分
print("{!s}".format(datetime.date(datetime.strptime(date3, '%Y-%m-%d'))))
print("{!s}".format(datetime.date(datetime.strptime(date4, '%B %d, %Y'))))
#在转换成datetime格式后,只返回date的内容
# 使用方括号创建一个列表
# 用len()计算列表中元素的数量
# 用max()和min()找出最大值和最小值
# 用count()计算出列表中某个值出现的次数
a_list = [1, 2, 3]
print("{}".format(a_list))
print("a_list has {} elements.".format(len(a_list)))
print("the maximum value in a_list is {}.".format(max(a_list)))
print("the minimum value in a_list is {}.".format(min(a_list)))
another_list = ['printer', 5, ['star', 'circle', 9]]
print("{}".format(another_list))
print("another_list also has {} elements.".format(len(another_list)))
print("5 is in another_list {} time.".format(another_list.count(5)))
print("{0}".format(a_list[0]))
print("{0}".format(a_list[-1]))
#切片
print("{}".format(a_list[0:2]))
print("{}".format(a_list[:2]))
print("{}".format(a_list[1:]))
#连接
a_longer_list = a_list + another_list print("{}".format(a_longer_list))
检验某一元素是否在该列表中
a = 2 in a_list
print("{}".format(a))
if 2 in a_list:
print("2 is in {}.".format(a_list))
b = 6 not in a_list
print("{}".format(b))
if 6 not in a_list:
print("6 is not in {}.".format(a_list))
# 使用append()向列表末尾追加一个新元素
# 使用remove()从列表中删除一个特定元素
# 使用pop()从列表末尾删除一个元素
a_list.append(4)
a_list.append(5)
a_list.append(6)
print("{}".format(a_list))
a_list.remove(5)
print("{}".format(a_list))
a_list.pop()
a_list.pop()
print("{}".format(a_list))
# 使用reverse()原地反转一个列表会修改原列表
# 要想反转列表同时又不修改原列表,可以先复制列表
a_list.reverse()
print("{}".format(a_list))
a_list.reverse()
print("{}".format(a_list))
# 使用sort()对列表进行原地排序会修改原列表
# 要想对列表进行排序同时又不修改原列表,可以先复制列表
unordered_list = [3, 5, 1, 7, 2, 8, 4, 9, 0, 6]
print("{}".format(unordered_list))
list_copy = unordered_list[:]
list_copy.sort()
print("{}".format(list_copy))
print("{}".format(unordered_list))
# 使用sorted()对一个列表集合按照列表中某个位置的元素进行排序
my_lists = [[1,2,3,4], [4,3,2,1], [2,4,1,3]]
my_lists_sorted_by_index_3 = sorted(my_lists, key=lambda index_value:index_value[3])
#表示使用索引位置为3的值(也就是列表中的第四个元素)对列表进行排序
#sorted 函数返回一个新的排好序的列表,并不改变原列表的元素顺序。
print("{}".format(my_lists_sorted_by_index_3))
from operator import itemgetter
#导入operator函数中的itemgetter函数后,可以使用每个列表中多个索引位置的值对列表集合进行排序
# 使用itemgetter()对一个列表集合按照两个索引位置来排序
my_lists = [[123,2,2,444], [22,6,6,444], [354,4,4,678], [236,5,5,678],[578,1,1,290], [461,1,1,290]]
my_lists_sorted_by_index_3_and_0 = sorted(my_lists, key=itemgetter(3,0))
#先按照索引位置 3 中的值对列表进行排序,然后,在这个排序基础上,按照索引位置 0 中的值对列表进一 步排序
print("{}".format(my_lists_sorted_by_index_3_and_0))
元组除了不能被修改之外,其余特点与列表非常相似
# 使用圆括号创建元组
my_tuple = ('x', 'y', 'z')
print("{}".format(my_tuple))
print("my_tuple has {} elements".format(len(my_tuple)))
print("{}".format(my_tuple[1]))
longer_tuple = my_tuple + my_tuple
print("{}".format(longer_tuple))
#一些适用于列表的函数也能适用于元组
# 使用赋值操作符左侧的变量对元组进行解包
one, two, three = my_tuple
print(" {0} {1} {2}".format(one, two, three))
#分别把x\y\z解包成为变量one、two、three
var1 = 'red'
var2 = 'robin'
print("{} {}".format(var1, var2))
# 在变量之间交换彼此的值
var1, var2 = var2, var1
print("{} {}".format(var1, var2))
my_list = [1, 2, 3]
my_tuple = ('x', 'y', 'z')
print("{0}".format(tuple(my_lists)))
print("{0}".format(list(my_tuple)))
Python 中的字典本质上是包含各种带有唯一标识符的成对信息的列表。
字典与列表的区别:
# 使用花括号创建字典
# 用冒号分隔键-值对
# 用len()计算出字典中键-值对的数量
empty_dict = { }
a_dict = {'one':1, 'two':2, 'three':3}
print("{}".format(a_dict))
print("a_dict has {!s} elements".format(len(a_dict)))
another_dict = {'x':'printer', 'y':5, 'z':['star', 'circle', 9]}
print("{}".format(another_dict))
print("another_dict also has {!s} elements".format(len(another_dict)))
# 使用键来引用字典中特定的值
print("{}".format(a_dict['two']))
print("{}".format(another_dict['z']))
#字典名称、方括号、特定的键值
# 使用copy()复制一个字典
a_new_dict = a_dict.copy()
print("{}".format(a_new_dict))
# 使用keys()、values()和items()
# 分别引用字典中的键、值和键-值对
print("{}".format(a_dict.keys()))
print("{}".format(a_dict.values()))
print("{}".format(a_dict.items()))
#运行的结果都是一个列表
#也可以直接生成变量
a_dict_keys = a_dict.keys()
print("{}".format(a_dict_keys))
if 'y' in another_dict:
print("y is a key in another_dict {}.".format(another_dict.keys()))
if 'c' not in another_dict:
print("c is not a key in another_dict: {}.".format(another_dict.keys()))
print("{!s}".format(a_dict.get('three')))
print("{!s}".format(a_dict.get('four')))
#如果没有这个键值,则返回none
print("{!s}".format(a_dict.get('four', 'Not in dict')))
#如果没有该键值,则返回Not in dict
# 使用sorted()对字典进行排序
# 要想对字典排序的同时不修改原字典
# 先复制字典
print("{}".format(a_dict))
dict_copy = a_dict.copy()
ordered_dict1 = sorted(dict_copy.items(), key=lambda item: item[0])
#先利用items()生成了键值元组列表
#item[0]将字典中的键-值对按照字典键值升序排序
print("(order by keys): {}".format(ordered_dict1))
ordered_dict2 = sorted(dict_copy.items(), key=lambda item: item[1])
#item[1]将字典中的键-值对按照字典值升序排序
print("(order by values): {}".format(ordered_dict2))
ordered_dict3 = sorted(dict_copy.items(), key=lambda x: x[1], reverse=True)
#按字典值进行排序,reverse=True降序排列
print("(order by values, descending): {}".format(ordered_dict3))
ordered_dict4 = sorted(dict_copy.items(), key=lambda x: x[1], reverse=False)
print("(order by values, ascending): {}".format(ordered_dict4))
if x > 4 or x != 9:
print("{}".format(x))
else:
print("x is not greater than 4")
# if-elif-else语句
if x > 6:
print("x is greater than six")
elif x > 4 and x == 5:
print("{}".format(x*x))
else:
print("x is not greater than 4")
y = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
z = ['Annie', 'Betty','Claire', 'Daphne','Ellie', 'Franchesca','Greta','Holly', 'Isabel', 'Jenny']
for month in y:
print("{!s}".format(month))
#展示了基本语法,即 for variable in sequence,做某事
# variable 是一个临时占位符,表示序列中的各个值,并且只在 for 循环中有意义
# 在这个示例中,变量名为 month。sequence是你要进行迭代的序列的名称
# 同样在这个示例中,序列名为 y,是一个月份列表
for i in range(len(z)):
print("{0!s}: {1:s}".format(i, z[i]))
#对于0~9 的整数序列中的一个整数 i,打印出整数 i,再打印一个空格
# 然后打印出列表 z 中索引值为 i 的元素值
for j in range(len(z)):
if y[j].startswith('J'):
print("{!s}".format(y[j]))
#y的索引值如果是以J开头,则打印
for key, value in another_dict.items():
print("{0:s}, {1}".format(key, value))
#在字典的键和值之间进行迭代和引用的方法
列表生成式
# 使用列表生成式选择特定的行
my_data = [[1,2,3], [4,5,6], [7,8,9]]
rows_to_keep = [row for row in my_data if row[2] > 5]
#方括号
#这里的row只是一个暂时的变量名,只在该式中起作用,且可以更改
print("{}".format(rows_to_keep))
#保留my_data中索引位置为2(即第三个位置)的值大于5的列表,这里是[4,5,6], [7,8,9]
集合生成式
# 使用集合生成式在列表中选择出一组唯一的元组
my_data = [(1,2,3), (4,5,6), (7,8,9), (6,8,9)]
set_of_tuples1 = {one for one in my_data}
#花括号
#这里的one只是一个临时变量名
#对于my_data中的每个元组,如果它是唯一的,则保留这个元组
print("(set comprehension): {}".format(set_of_tuples1))
set_of_tuples2 = set(my_data)
print("(set function): {}".format(set_of_tuples2))
#使用set函数能达到同样的效果
字典生成式
# 使用字典生成式选择特定的键-值对
my_dictionary = {'customer1': 7, 'customer2': 9, 'customer3': 11}
my_results = {key : value for key, value in my_dictionary.items() if value > 10}
#key:value for key表示键—值对格式,后面是一个条件句
#对于my_dictionay 中的每个键-值对,如果值大于10,则保留这个键-值对
print("(dictionary comprehension): {}".format(my_results))
x = 0
while x < 11:
print("{!s}".format(x))
x += 1
#正常的运算方式
def getMean(numericValues):
if len(numericValues) > 0:
return sum(numericValues)/len(numericValues)
else:
return float('nan')
my_list = [2, 2, 4, 4, 6, 6, 8, 8]
print("(mean): {!s}".format(getMean(my_list)))
try except
#try except
# 计算一系列数值的均值
def getMean(numericValues):
return sum(numericValues)/len(numericValues)
my_list2 = [ ]
try:
print("{}".format(getMean(my_list2)))
except ZeroDivisionError as detail:
print("(Error): {}".format(float('nan')))
print("(Error): {}".format(detail))
#要想使用try-except 代码块,需要将你要执行的代码放在try 代码块中
#使用 except 代码块来处理潜在的错误并打印出错误信息来帮助你理解程序错误
try-excep-else-finally
# 完整形式
try:
result = getMean(my_list2)
except ZeroDivisionError as detail:
print ("(Error): " + str(float('nan')))
print ("(Error):", detail)
else:
print ("(The mean is):", result)
finally:
print ("(Finally): The finally block is executed every time")
#如果传递给 try 代码块中的 getMean() 函数的数值序列中包含任意数值
# 那么这些数值的均值就会被赋给 try 代码块 中的变量 result
# 接着执行 else 代码块
f = open('C:/Users/Administrator/Desktop/file.txt','w+')
f.write('hello world')
如果再次运行程序,txt文件中的内容不会继续添加,可以修改模式参数为’r+’,便可一直写入文件。
f = open('C:/Users/Administrator/Desktop/file.txt','r')
content = f.read()
print(content)
# result hello world
另一种打开文件的方式(利用sys.argv())
import sys
print(sys.argv[0])
print(sys.argv[1])
#先了解什么是argv[],其引用路径是什么?
input_file = sys.argv[1]
filereader = open(input_file, 'r')
#'r'表示以只读模式打开input_file中的各行
for row in filereader:
print(row.strip())
#每次只读取filereader中的一行,并且去掉两端的空格、制表符和换行符
filereader.close()
#关闭filereader对象
上面的方式打开文件会使得文件一直处于打开状态,直到使用 close 函数明确地关闭或直到脚本结束。所以一般使用with来创建文件对象,在with结束之后会自动关闭对象。
inputfile=argv[1]
with open (inputfile,'r',newline='') as filereader:
for row in filereader:
print("{}".format(row.strip()))
import sys
import os
#os.path.join 函数可以巧妙地将一个或多个路径成分连接在一起
import glob
#glob 模块可以找出与特定模式相匹配的所有路径名
print("Output #145:")
inputPath = sys.argv[1]
#注意这里要把参数改为目录路径名,而非前面的文件路径名
print(inputPath)
for input_file in glob.glob(os.path.join(inputPath,'*.txt')):
with open(input_file, 'r', newline='') as filereader:
for row in filereader:
print("{}".format(row.strip()))
#使用os.path.join 函数和 glob.glob 函数来找出符合特定模式的某个文件夹下面的所有文件
#指向这个文件夹的路径包含在变量inputpath中
#os.path.join()函数将这个文件夹路径和这个文件夹中所有符合特定模式的文件名连接起来
#这种特定模式可以由glob.glob函数扩展
import sys
my_letters=['a','b','c','d','e','f','g','h','i','j']
outputfile=sys.argv[1]
filewriter = open(outputfile, 'w')
#先打开将要被写入数据的文本
for i in range(len(my_letters)):
if i<len(my_letters)-1:
filewriter.write(my_letters[i]+'\t')
else:
filewriter.write(my_letters[i]+'\n')
filewriter.close()
#字符串之间的间隔方式为制表符,也可以改成其他符号
#最后一个字符串的间隔方式为换行符
#这种方式会覆盖掉以前文本中存入的数据
my_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
output_file=sys.argv[1]
filewriter = open(output_file,'a')
#这里后面的参数写的是'a',表示append,在保留以前数据的情况下,添加新数据
for i in range(len(my_numbers)):
if i<len(my_numbers)-1:
filewriter.write(str(my_numbers[i])+',')
else:
filewriter.write(str(my_numbers[i])+'\n')
filewriter.close()
f = open('C:/Users/Administrator/Desktop/file.txt','r')
content = f.read()
print(content)
f.close()
#本章练习
a=[1,2,3]
b=[4,5,6]
c=[4,6,["we","have","park"]]
d=a+b+c
for i in range(len(d)):
print ("{!s} {}".format(i,d[i]))
a=["one","two","three","four","six","seven","eight"]
b=[1,2,3,4,5,6,7,8]
one_dict={ }
for i in range(len(a)):
if a[i] not in one_dict:
one_dict[a[i]]=b[i]
for key,value in one_dict.items():
print("{}:{}".format(key,value))
list_of_lists = [['cow','pig','horse'], ['dog','cat','gold fish'],['lion','elephant','gorilla']]
for animal_list in list_of_lists:
max_index = len(animal_list)
output = ''
for index in range(len(animal_list)):
if index < (max_index-1):
output += str(animal_list[index])+','
else:
output += str(animal_list[index])+'\n'
print(output)