python467教程_Magnus Lie Hetland的《Python基础教程(第3版)》自学笔记(持续更新中)...

转载请注明原创出处,谢谢!

如果读完觉得有收获的话,欢迎点赞加关注。

Python基础教程.jpg

快速上手:基础知识

交互式解释器

在Python交互式解释器的提示符>>>后面输入help()可以获取指南,在IDLE中,还可以用F1来获取帮助信息。

help()

Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out

the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing

Python programs and using Python modules. To quit this help utility and

return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type

"modules", "keywords", "symbols", or "topics". Each module also comes

with a one-line summary of what it does; to list the modules whose name

or summary contain a given string such as "spam", type "modules spam".

算法是什么

算法是由对象和语句所组成。对象是数、表达式、变量

数和表达式

十六进制、八进制和二进制表示法都是以0打头的

0xAF

175

0o10

8

0b1011010010

722

变量

赋值-assignment,变量是表示(或指向)特定值的名称。

语句

语句相当于菜谱中的操作说明,表达式是一些东西,而语句做一些东西。所有语句的一个根本特征:执行修改操作。

赋值语句是最重要的语句,变量就像是临时“存储区”,其真正的威力在于无需知道它们存储的值就能操作它们。

获取用户输入

函数

模块

回到未来

import __future__

保存并执行程序

从命令提示符运行Python脚本

c:\python hello.py

File "", line 1

c:\python hello.py

^

SyntaxError: unexpected character after line continuation character

让脚本像普通程序一样

在有些情况下,你希望能够像执行其他程序(如web浏览器或文本编辑器)一样执行Python脚本,而无需显式地使用Python解释器。

UNIX提供了这种目标的标准方式:让脚本的第一行以字符序列#!(称为pound bang或shebang)开始,并在它后面指定用于对脚本进行解释的程序(这里是Python)的绝对路径。

例如:#!/usr/bin/evn python

要想普通程序一样运行脚本,还必须将Python的脚本文件必成可执行的。

如:$ chmod a+x hello.py

然后运行: $ hello.py

如果愿意,可对文件进行重命名并删除扩展名.py,使其看起来更像普通程序。

注释

在代码中,#号后面到行尾的所有内容都将被忽略。

字符串

单引号字符串以及对引号转义

反斜杠 \

拼接字符串

"Let's say " '"Hello, world"'

'Let\'s say "Hello, world"'

"Hello " + "world!"

'Hello world!'

x = "Hello, "

y = "world!"

x + y

'Hello, world!'

字符串表示str和repr

"Hello World!"

'Hello World!'

print("Hello World!")

Hello World!

"Hello, \nworld!"

'Hello, \nworld!'

print("Hello, \nworld!")

Hello,

world!

print(repr("Hello, \nworld!"))

'Hello, \nworld!'

print(str("Hello, \nworld!"))

Hello,

world!

长字符串、原始字符串和字节

print('''This is a very long string. It continues here.

And it's not over yet. "Hello, world!"

Still here.''')

This is a very long string. It continues here.

And it's not over yet. "Hello, world!"

Still here.

长字符串

print("Hello, \

world!")

Hello, world!

1 + 2 + \

4 + 5

12

print \

("Hello, world!")

Hello, world!

原始字符串

path = "C:\nowhere"

path

'C:\nowhere'

print(path)

C:

owhere

print("C:\\nowhere")

C:\nowhere

print(r"C:\nowhere")

C:\nowhere

print(rpath)

---------------------------------------------------------------------------

NameError Traceback (most recent call last)

in

----> 1 print(rpath)

NameError: name 'rpath' is not defined

print(r(path))

---------------------------------------------------------------------------

NameError Traceback (most recent call last)

in

----> 1 print(r(path))

NameError: name 'r' is not defined

print(r"C:\Program Files\fnord\foo\bar\baz\frozz\bozz")

C:\Program Files\fnord\foo\bar\baz\frozz\bozz

print(r'Let\'s go!')

Let\'s go!

原始字符串的最后一个字符不能是反斜杠“\”

print(r'This is illegal\')

File "", line 1

print(r'This is illegal\')

^

SyntaxError: EOL while scanning string literal

显示以反斜杠\结尾的原始字符的方法之一:

print(r'C:\Program Files\foo\bar' '\\')

C:\Program Files\foo\bar\

print('a' 'b')

ab

Unicode, bytes和bytearray

"\u00C6"

'Æ'

"\U0001F60A"

'😊'

"This is a cat: \N{Cat}"

'This is a cat: 🐈'

"This is a cat: \N{Dog}"

'This is a cat: 🐕'

"This is a cat: \N{Fish}"

'This is a cat: 🐟'

列表和元组

数据结构是以某种方式(如通过编号)组合起来的数据元素(如数、字符乃至其他数据结构)集合。

序列概述

edward = ['Edward Gumby', 42]

john = ['John Smith', 50]

database = [edward, john]

database

[['Edward Gumby', 42], ['John Smith', 50]]

通用的序列操作

有几种操作适用于所有序列,包括索引、切片、相加、相乘和成员资格检查。

索引

greeting = "Hello"

greeting[0]

'H'

greeting = "Hello"

greeting[-1]

'o'

'Hello'[-1]

'o'

fourth = input('Year: ')[3]

Year: 2019

fourth

'9'

切片

tag = 'Python web site'

tag[9:30]

'http://www.python.org'

tag[32:-4]

'Python web site'

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[3:6]

[4, 5, 6]

numbers[0:1]

[1]

绝妙的简写

numbers[7:10]

[8, 9, 10]

numbers[-3:-1]

[8, 9]

numbers[-3:0]

[]

numbers[-3:]

[8, 9, 10]

numbers[:3]

[1, 2, 3]

numbers[:]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

更大的步长

numbers[0:10:1]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[0:10:2]

[1, 3, 5, 7, 9]

numbers[3:6:3]

[4]

numbers[::4]

[1, 5, 9]

numbers[8:3:-1]

[9, 8, 7, 6, 5]

numbers[10:0:-2]

[10, 8, 6, 4, 2]

numbers[0:10:-2]

[]

numbers[::-2]

[10, 8, 6, 4, 2]

numbers[5::-2]

[6, 4, 2]

numbers[:5:-2]

[10, 8]

序列相加

[1, 2, 3] + [4, 5, 6]

[1, 2, 3, 4, 5, 6]

'Hello, ' + 'world!'

'Hello, world!'

[1, 2, 3] + 'world!'

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

in

----> 1 [1, 2, 3] + 'world!'

TypeError: can only concatenate list (not "str") to list

乘法

'python' * 5

'pythonpythonpythonpythonpython'

[42] * 10

[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

None、空列表和初始化(如将列表的长度初始化为10)

sequence = [None] * 10

sequence

[None, None, None, None, None, None, None, None, None, None]

代码清单2-3

sentence = input("Sentence: ")

screen_width = 80

text_width = len(sentence)

box_width = text_width + 6

left_margin = (screen_width - box_width) // 2

print()

print(' ' * left_margin + '+' + '-' * (box_width - 2) + '+')

print(' ' * left_margin + '| ' + ' ' * text_width + ' |')

print(' ' * left_margin + '| ' + sentence + ' |')

print(' ' * left_margin + '| ' + ' ' * text_width + ' |')

print(' ' * left_margin + '+' + '-' * (box_width - 2) + '+')

print()

Sentence: He's a very naughty boy!

+----------------------------+

| |

| He's a very naughty boy! |

| |

+----------------------------+

成员资格

permissions = 'rw'

'w' in permissions

True

'x' in permissions

False

users = ['mlh', 'foo', 'bar']

input('Enter your user name') in users

Enter your user namevictor

False

subject = '$$$ Get rich now!!! $$$'

'$$$' in subject

True

'P' in "Python"

True

代码清单2-4 序列成员资格示例

# 检查用户名和PIN码

database = [

['albert', '1234'],

['dilber', '4242'],

['smith', '7524'],

['jones', '9843']

]

username = input('User name: ')

pin = input('PIN code: ')

if [username, pin] in database:

print('Access granted.')

else:

print('Not Authorized!')

User name: smith

PIN code: 7524

Access granted.

长度、最小值和最大值

len,min和max是内置函数

numbers = [100, 34, 678]

len(numbers)

3

max(numbers)

678

min(numbers)

34

max(2, 3)

3

min(9, 3, 2, 5)

2

列表:Python的主力

函数list

list('Hello')

['H', 'e', 'l', 'l', 'o']

mylist = list('Hello')

print(mylist)

''.join(mylist)

['H', 'e', 'l', 'l', 'o']

'Hello'

''.join(['a', 'b', 'c', 'd'])

'abcd'

基本的列表操作

修改列表:给元素赋值

x = [1, 1, 1]

x[1] = 2

x

[1, 2, 1]

mylist = [None] * 5

mylist[4] = '初始化赋值'

mylist

[None, None, None, None, '初始化赋值']

删除元素

name = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']

name

del name[2]

name

['Alice', 'Beth', 'Dee-Dee', 'Earl']

给切片赋值

name = list('Perl')

name

['P', 'e', 'r', 'l']

name[2:] = list('ar')

name

['P', 'e', 'a', 'r']

name = list('Perl')

name[1:] = list("ython")

name

['P', 'y', 't', 'h', 'o', 'n']

numbers = [1, 5]

numbers[1:1] = [2, 3, 4]

numbers

[1, 2, 3, 4, 5]

numbers = [1, 5]

numbers[1:1] = list("python")

numbers

[1, 'p', 'y', 't', 'h', 'o', 'n', 5]

numbers = [1, 5]

numbers[0:0] = list("python")

numbers

['p', 'y', 't', 'h', 'o', 'n', 1, 5]

上面是替换了一个空切片[1:1]

numbers = [1, 5]

numbers[0:1] = list("python")

numbers

['p', 'y', 't', 'h', 'o', 'n', 5]

用一个空切片替换某些元素,达到删除元素的目的

numbers = [1, 2, 3, 4, 5]

numbers[1:4] = []

numbers

[1, 5]

numbers = [1, 2, 3, 4, 5]

del numbers[1:4]

numbers

[1, 5]

给使用步长的切片赋值

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[1:10:2] = list("pytho")

numbers

[1, 'p', 3, 'y', 5, 't', 7, 'h', 9, 'o']

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[10:0:-2]

[10, 8, 6, 4, 2]

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[10:0:-2] = list('vwang')

numbers

[1, 'g', 3, 'n', 5, 'a', 7, 'w', 9, 'v']

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[10:0:-2] = [31, 32, 33, 34, 35]

numbers

[1, 35, 3, 34, 5, 33, 7, 32, 9, 31]

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[0:0] = [31, 32, 33, 34, 35]

numbers

[31, 32, 33, 34, 35, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

列表方法

方法是与对象(列表、数、字符串等)联系紧密的函数。通常的调用方法是:object.method(arguments

方法调用与函数调用很像,只是在方法名前加上了对象和句点。

append

lst = [1, 2, 3]

lst.append(4)

lst

[1, 2, 3, 4]

lst.append(list('Python'))

lst

[1, 2, 3, 4, ['P', 'y', 't', 'h', 'o', 'n']]

lst = [1, 2, 3, 4]

words = "Python"

for i in list(words):

print(i, end="")

lst.append(i)

lst

Python

[1, 2, 3, 4, 'P', 'y', 't', 'h', 'o', 'n']

clear

方法clear表示就地清空列表的内容

lst = [1, 2, 3]

lst.clear()

lst

[]

copy

方法copy复制列表,而常规复制(即不是用方法copy进行的复制,用=号进行的复制)只是将另一个名称关联到源列表,就像别名。

常规复制(即不是用方法copy进行的复制,用=号进行的复制):

a = [1, 2, 3]

b = a

b[1] = 4

a

[1, 4, 3]

要让a和b指向不同的列表,就必须将b关联的a的副本上

a= [1, 2, 3]

b = a.copy()

b[1] = 4

print(a, b)

[1, 2, 3] [1, 4, 3]

count

方法count计算指定的元素在列表中出现的次数,而不是表示列表中所有元素的个数。

["to", "be", "or", "not", 'to', 'be'].count('to')

2

x = [[1, 2], 1, 1, [2, 1, [1, 2]]]

x.count(1)

2

x.count([1, 2])

1

extend

方法Extend让你能够同时将多个值附加到列表末尾。

a = [1, 2, 3]

b = [4, 5, 6]

a.extend(b)

a

[1, 2, 3, 4, 5, 6]

a = [1, 2, 3]

b = [4, 5, 6]

a + b

[1, 2, 3, 4, 5, 6]

a

[1, 2, 3]

a = [1, 2, 3]

b = [4, 5, 6]

a = a + b

a

[1, 2, 3, 4, 5, 6]

a = [1, 2, 3]

b = [4, 5, 6]

a[len(a):] = b

a

[1, 2, 3, 4, 5, 6]

index

方法index在列表中查找指定值第一次出现的索引

knights = ["We", "are", "the", "knights", "who", "say", "ni"]

knights.index("who")

4

knights.index("herring")

---------------------------------------------------------------------------

ValueError Traceback (most recent call last)

in

----> 1 knights.index("herring")

ValueError: 'herring' is not in list

knights[4]

'who'

insert

方法insert用于将一个对象插入列表

numbers = [1, 2, 3, 5, 6, 7]

numbers.insert(3, 'four')

numbers

[1, 2, 3, 'four', 5, 6, 7]

numbers = [1, 2, 3, 5, 6, 7]

numbers[3:3] = ['four']

numbers

[1, 2, 3, 'four', 5, 6, 7]

pop

方法pop从列表中删除一个元素(默认为最后一个元素),并返回这一元素。方法pop是唯一的一种列表的方法,既修改列表又返回一个非None值

x = [1, 2, 3]

x.pop()

3

x

[1, 2]

x.pop(0)

1

x

[2]

x.pop()

2

x

[]

x.pop()

---------------------------------------------------------------------------

IndexError Traceback (most recent call last)

in

----> 1 x.pop()

IndexError: pop from empty list

使用pop可实现一种常见的数据结构-栈(stack)。栈就像一叠盘子,你可以在上面添加盘子,还可以从上面取走盘子。最后加入的盘子最先取走,这被称为后进先出(LIFO)。

push和pop是普遍接受的两种栈的操作(加入和取走)的名称。Python没有提供push,但可以用append来代替。方法pop和方法append的效果相反,因此将刚取走的值再加入(或称附加)后,得到的栈与原来的栈相同。

x = [1, 2, 3]

x.append(x.pop())

x

[1, 2, 3]

remove

方法remove用于删除第一个指定值的元素

x = ["to", "be", "or", "not", "to", "be"]

x.remove("be")

x

['to', 'or', 'not', 'to', 'be']

x.remove("bee")

---------------------------------------------------------------------------

ValueError Traceback (most recent call last)

in

----> 1 x.remove("bee")

ValueError: list.remove(x): x not in list

reverse

方法reverse按相反的顺序排列列表中的元素。

x = [1, 2, 3]

x.reverse()

x

[3, 2, 1]

如果要按相反的顺序迭代序列,可使用函数reversed。这个函数不返回列表,而是返回一个迭代器。可以使用list将返回的对象转换成列表。

x = [1, 2, 3]

list(reversed(x))

[3, 2, 1]

sort

方法sort用于对列表就地排序。就地排序意味着对原来的列表进行修改,是其元素按顺序排列,而不是返回排序后的列表的副本。

x = [4, 6, 2, 1, 7, 9]

x.sort()

x

[1, 2, 4, 6, 7, 9]

x = [4, 6, 2, 1, 7, 9]

y = x.sort() # Don't do this!

print(y)

None

x = [4, 6, 2, 1, 7, 9]

y = x.copy()

y.sort()

x

[4, 6, 2, 1, 7, 9]

y

[1, 2, 4, 6, 7, 9]

x = [4, 6, 2, 1, 7, 9]

y = sorted(x)

x

[4, 6, 2, 1, 7, 9]

y

[1, 2, 4, 6, 7, 9]

sorted("Python")

['P', 'h', 'n', 'o', 't', 'y']

高级排序

方法sort接受两个参数:key和reverse。这两个参数通常是按名称指定的,称为关键字参数。

参数key类似于参数cmp:将其设置为一个用于排序的函数。然而,不会直接使用这个函数来判断以恶元素是否币另一个元素小,而是用它来为每个元素创建一个键,再根据这些键对元素进行排列。

x = ["aardvark", "abalone", "acme", "add", "aerate"]

x.sort(key=len)

x

['add', 'acme', 'aerate', 'abalone', 'aardvark']

参数reverse, 只需将其指定为一个真值(True或False)以指出是否要按相反的顺序对列表进行排序。

x = [4, 6, 2, 1, 7, 9]

x.sort(reverse=True)

x

[9, 7, 6, 4, 2, 1]

函数sorted也接受参数key和reverse,在很多情况下,将参数key设置为一个自定义的函数很有用。

元组:不可修改的序列

1, 2, 3

(1, 2, 3)

"p", "y"

('p', 'y')

(1, 2, 3)

(1, 2, 3)

()

()

42

42

42,

(42,)

(42,)

(42,)

3 * (42 + 2)

132

3 * (42 + 2,)

(44, 44, 44)

tuple([1, 2, 3])

(1, 2, 3)

list("python")

['p', 'y', 't', 'h', 'o', 'n']

list(892)

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

in

----> 1 list(892)

TypeError: 'int' object is not iterable

x = 1, 2, 3

x

x[1]

2

x[2]

3

x[0:2]

(1, 2)

使用字符串

字符串基本操作

所有标准序列操作(索引、切片、乘法、成员资格检查、长度、最小值和最大值)都是适用于字符串,但字符串是不可变的,所有的元素赋值或切片赋值都是非法的。

website = "http://www.python.org"

website{-3:} = "com"

File "", line 3

website{-3:} = "com"

^

SyntaxError: invalid syntax

max(website)

'y'

min(website)

'.'

len(website)

21

"py" in website

True

设置字符串的格式:精简版

字符串格式:%s

format = "Hello, %s. %s enough for ya?"

values = ("world", "Hot")

format % values

'Hello, world. Hot enough for ya?'

"Hello, %s." % "world"

'Hello, world.'

"Hello, the %srd world!" % 3

'Hello, the 3rd world!'

浮点数格式:如%.3f

"Hello, the %.3f world!" % 3

'Hello, the 3.000 world!'

字符串模板,但是要导入string模块

from string import Template

tmp1 = Template("Hello, $who! $what enough for ya?")

tmp1.substitute(who="Mars", what="Dusty")

'Hello, Mars! Dusty enough for ya?'

字符串方法.format()

最简单的情况,被替换字段没有名称或使用.format()括号中参数值的索引(顺序)做名称

"{}, {} and {}".format("first", "second", "third")

'first, second and third'

"{0}, {1} and {2}".format(100, 200, "AAA")

'100, 200 and AAA'

如果被替换字段使用函数.format()括号中参数值的索引(顺序)的方式,.format()点号左边的被替换字段不需要按参数值的索引顺序排列,同时可以重复

"{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")

'to be or not to be'

给字段命名,.format()点号左边的被替换字段也不需要按参数值的索引顺序排列,同时也可以重复

from math import pi

"{name} is approximately {value:.2f} and {value:.10f} and {value}.".format(value=pi, name="π")

'π is approximately 3.14 and 3.1415926536 and 3.141592653589793.'

如果函数.format()参数的变量名与被替换字段变量名同名,还可以使用一种简写,可以使用f"字符串"的形式-在字符串前面加上f

from math import e

f"Euler's constant is roughly {e}."

"Euler's constant is roughly 2.718281828459045."

test = "test123"

f"This is just a {test}"

'This is just a test123'

from math import e

"Euler's constant is roughly {e}".format(e=e)

"Euler's constant is roughly 2.718281828459045"

from math import e

"Euler's constant is roughly {value}".format(value=e)

"Euler's constant is roughly 2.718281828459045"

设置字符串的格式:完整版

字符串包含了有关如何设置格式的信息,而这些信息是使用一种微型格式指定语言(mini-language)指定的。每个值都被插入字符串中,以替换用大括号括起来的被替换字段。要在最终结果中包含大括号,可以在格式字符串中使用两个大括号(即{{与}}),且函数.format()参数为空来指定

"{{ceci n'est pas une replacement field}}".format()

"{ceci n'est pas une replacement field}"

被替换字段名

"{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)

'3 1 4 2'

如果函数.format()混合使用位置参数和关键字参数,那么位置参数(被替换字段的大括号内的内容为空)必须在关键字参数的前面

"{foo} {} {bar} {}".format(bar=4, foo=3, 1, 2)

File "", line 1

"{foo} {} {bar} {}".format(bar=4, foo=3, 1, 2)

^

SyntaxError: positional argument follows keyword argument

"{foo} {} {bar} {}".format(1, bar=4, 2, foo=3)

File "", line 1

"{foo} {} {bar} {}".format(1, bar=4, 2, foo=3)

^

SyntaxError: positional argument follows keyword argument

fullname = ["Alfred", "Smoketoomuch"]

"Mr {name[1]}".format(name=fullname)

'Mr Smoketoomuch'

import math

tmpl = "The {mod.__name__} module defines the value {mod.pi} for π"

tmpl.format(mod=math)

'The math module defines the value 3.141592653589793 for π'

基本转换

添加设置其格式的指令,转换标志,!f, !r, !a,分别表示str、repr和ascii转换

print("{pi!s} {pi!r} {pi!a}".format(pi="π"))

π 'π' '\u03c0'

定点数

"The number is {num}".format(num=42)

'The number is 42'

"The number is {num:f}".format(num=42)

'The number is 42.000000'

"The number is {num:b}".format(num=42)

'The number is 101010'

宽度、精度和千位分隔符

宽度是使用整数指定的

"{num:10}".format(num=3)

' 3'

"{name:10}".format(name="Bob")

'Bob '

精度也是用整数指定的,但需要在它前面加上一个表示小数点的句点

from math import pi

"Pi day is {pi:.2f}".format(pi=pi)

'Pi day is 3.14'

同时指定宽度和精度

"{pi:10.2f}".format(pi=pi)

' 3.14'

"{:.5}".format("Guido van Rossum")

'Guido'

"One googol is {:,}".format(10**100)

'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'

符号、对齐和用0填充

在同一栏中包含自串和数字时,想要修改默认对齐方式,那么在指定宽度和精度的数的前面,可以添加一个标志,这个标志可以时零、加号、减号或空格。

零表示使用零来填充数字。

from math import pi

"{:10.2f}".format(pi)

' 3.14'

"{:010.2f}".format(pi)

'0000003.14'

要指定左对齐、右对齐和居中,可分别使用和^。

print("{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}".format(pi))

3.14

3.14

3.14

可以使用填充字符来扩充对齐说明符,这样将使用自定的字符而不是默认的空格来填充

"{:$^15}".format(" WIN BIG ")

'$$$ WIN BIG $$$'

"{:#^15}".format(" WIN BIG ")

'### WIN BIG ###'

"{:a^15}".format(" WIN BIG ")

'aaa WIN BIG aaa'

说明指示符=,它指定将填充字符放在符号和数字之间

print("{0:10.2f}\n{1:10.2f}".format(pi, -pi))

3.14

-3.14

print("{0:10.2f}\n{1:=10.2f}".format(pi,-pi))

3.14

- 3.14

如果要给正数加上符号,可以使用说明符+(将其放在对齐说明符后面,而不是默认的-,如果将符号说明符指定为空格,会在正数前面加上空格而不是+。

print("{0:-.2}\n{1:-.2}".format(pi, -pi))

3.1

-3.1

print("{0:+.2}\n{1:+.10}".format(pi, -pi))

+3.1

-3.141592654

print("{0: .2}\n{1: .2}".format(pi, -pi))

3.1

-3.1

最后一个要素是#号选项,可以将其放在符号说明符和宽度说明符之间(如果指定了这两种设置)。这个选项将触发另一种转换方式、转换细节随类型而异。例如对于二进制,八进制和十六进制转换。

二进制

"{:b}".format(42)

'101010'

八进制

"{:#b}".format(42)

'0b101010'

十六进制

"{:#x}".format(42)

'0x2a'

对于各个十进制数,它要求必须包含小数点(对于类型g,它保留小数点后面的零)。

"{:g}".format(42)

'42'

"{:#g}".format(42)

'42.0000'

代码清单3-1 字符串格式设置示例

# 代码清单3-1 字符串格式设置示例

# 根据指定的宽度打印格式良好的价格列表

width = int(input("Please enter width: "))

price_width = 10

item_width = width - price_width

header_fmt = "{{:{}}}{{:>{}}}".format(item_width, price_width)

# print(header_with)

fmt ="{{:{}}}{{:>{}.2f}}".format(item_width, price_width)

test_fmt = "{:}{:>.2f}".format(item_width, price_width)

print(fmt)

print(test_fmt)

print("=" * width)

# print(header_fmt.format("Item", "Price"))

print("-" * width)

print(fmt.format("Apple", 0.4))

print(fmt.format("Pear", 0.5))

print(fmt.format("Cantaloupes", 1.92))

print(fmt.format("Dried Apricots (16 oz.)", 8.0))

print(fmt.format("Prunes (4 lbs.)", 12))

print("=" * width)

Please enter width: 35

{:25}{:>10.2f}

2510.00

===================================

-----------------------------------

Apple 0.40

Pear 0.50

Cantaloupes 1.92

Dried Apricots (16 oz.) 8.00

Prunes (4 lbs.) 12.00

===================================

字符串方法

center

"The Middle by Jimmy Eat World".center(39)

' The Middle by Jimmy Eat World '

len("The Middle by Jimmy Eat World")

29

"The Middle by Jimmy Eat World".center(39, "*")

'*****The Middle by Jimmy Eat World*****'

find

方法find在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1

"with a moo-moo here, and a moo-moo there.".find("moo")

7

title = "Monty Python's Flying Circus"

title.find("Monty")

0

title.find('Python')

6

title.find("Flying")

15

title.find("Zirquss")

-1

subject = "$$$ Get rich now!!! $$$"

subject.find("$$$")

0

指定搜索的起点和终点,它们都是可选的

subject = "$$$ Get rich now!!! $$$"

subject.find("$$$")

0

subject.find("$$$", 1) # 只指定了起点

20

subject.find("!!!")

16

subject.find("!!!", 0, 16) # 同时指定了起点和重点

-1

起点和终点值指定的搜索范围包含起点,但不包含终点,这是Python惯用的做法

join

合并序列的元素

seq = [1, 2, 3, 4, 5]

sep = "+"

sep.join(seq)

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

in

1 seq = [1, 2, 3, 4, 5]

2 sep = "+"

----> 3 sep.join(seq)

TypeError: sequence item 0: expected str instance, int found

seq = ["1", "2", "3", "4", "5"]

sep.join(seq)

'1+2+3+4+5'

dirs = "", "usr", "bin", "env"

"/".join(dirs)

'/usr/bin/env'

print("C:" + "\\".join(dirs))

C:\usr\bin\env

lower

方法lower返回字符串的小写版本

"Trondheim Hammer Dance".lower()

'trondheim hammer dance'

if "Gumby" in ["gumby", "smith", "jones"]:

print("Found it!")

else:

print("It is not found!")

It is not found!

name = "Gumby"

if name.lower() in ["gumby", "smith", "jones"]:

print("Found it!")

Found it!

词首大写

方法一:.title(),但是它确定单词边界的方式可能导致结果不合理

"that's all, folks".title()

"That'S All, Folks"

方法而:使用模块string中的函数capwords

import string

string.capwords("that's all, folks")

"That's All, Folks"

replace

方法replace将指定子串都替换为另一个字符串, 并返回替换后的结果。

"This is a test".replace("is", "eez")

'Theez eez a test'

"This is a test".replace("is", "2")

'Th2 2 a test'

split

方法split用于将字符串拆分为序列,并返回该序列的列表

"1+2+3+4+5".split("+")

['1', '2', '3', '4', '5']

"This is a test".split(' ')

['This', 'is', 'a', 'test']

"/usr/bin/env".split("/")

['', 'usr', 'bin', 'env']

如果没有指定分隔符,那么将默认在单个或多个连续的空白字符(空格,制表符、换行符等)处进行拆分,且不论有多少个空白字符都只算一个

"Using the default".split()

['Using', 'the', 'default']

"Using the default".split()

['Using', 'the', 'default']

strip

方法strip是将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。

" internal whitespace is kept ".strip()

'internal whitespace is kept'

names = ["gumby", "smith", "jones"]

name = "gumby "

if name in names:

print("Found it")

else:

print("The name is wrong!")

The name is wrong!

if name.strip() in names:

print("Found it!")

Found it!

可以在一个字符串参数中指定要删除字符串开头和结尾的哪些字符

"*** SPAM * for * everyone!!! ***".strip("*")

' SPAM * for * everyone!!! '

"*** SPAM * for * everyone!!! ***".strip(" *!")

'SPAM * for * everyone'

translate

方法trsanlate与replace一样是要替换字符串的特定部分,但不同的是translate只能进行单字符替换。tranlate方法的优势在于能够同时替换多个字符,因此效率比replace高。

使用translate前必须创建一个转换表。 这个转换表指出了不同Unicode码点之间的转换关系。要创建转换表, 可对字符串类型str调用方法maketrans,这个方法接受两个参数:两个长度相同的字符串,它们指定要将左边的的字符串中的每个字符按从左向右的顺序都被替换成右边字符串中的相应位置的字符。也可以传入一个字典,将一些字符映射到其他字符(如果要删除这些字符,则映射到None。

table = str.maketrans('cs', 'kz')

table

{99: 107, 115: 122}

"this is an incredible test".translate(table)

'thiz iz an inkredible tezt'

调用方法maketrans时,还可以提供第三个参数,指定要将那些字符删除。

table = str.maketrans("cs", "kz", " ")

"this is an incredible test".translate(table)

'thizizaninkredibletezt'

判断字符串是否满足特定的条件

很多字符串方法都以is开头,如isspace、isdigit和issupper,它们判断字符串是否具有特定的性质。如果字符串具备特定的性质,这些方法就返回True,否则返回False。

当索引行不通时

通过名称来访由一系列值组合成的数据结构中的各个值的数据结构,叫做映射(mapping)

字典时Python中唯一的内置映射类型,其中值不按顺序排列,而是存储在键下。键可能是数字、字符串或元组

字典的用途

Python字典的一些用途:

表示国际象棋棋盘的状态,其中每个键都是由坐标组成的元组;

存储文件修改时间,其中的键为文件名;

数字电话/地址簿

# 假如由如下名单:

names = ["Alice", "Beth", "Cecil", "Dee-Dee", "Earl"]

# 要创建一个数据库,在其中存储上面这些人的电话号码,一种方法是再创建一个列表。

numbers = ["2341", "9102", "3158", "0142", "5551"]

# 查找Cecil的电话号码

numbers[names.index("Cecil")]

'3158'

## 创建和使用字典

phonebook = {"Alice": "2341", "Beth": "9102", "Cecil": "3158"}

phonebook["Cecil"]

'3158'

在字典(以及其他非Python内置的映射类型)中,字典中的键必须是独一无二的,而字典中的值无需如此。

函数dict

可以使用函数(类)dict从其他映射(如其他字典)或键-值对序列创建字典

items = [("name", "Gumby"), ("age", 42)]

d = dict(items)

d

{'name': 'Gumby', 'age': 42}

d["name"]

'Gumby'

d["age"]

42

还可以使用关键字实参来调用这个函数。

d = dict(name='Gumby', age=42)

d

{'name': 'Gumby', 'age': 42}

d = dict(name="Victor")

d

{'name': 'Victor'}

如果调用这个函数是没有提供任何实参,将返回一个空字典。

d = dict()

d

{}

基本的字典操作

字典包含的项(键-值对)的个数

d = dict(name="Victor", age=55)

len(d)

2

与键相对应的值

d["name"]

'Victor'

添加键-值对

d["telephone"] = "3434234"

d

{'name': 'Victor', 'age': 55, 'telephon': '3434234', 'telephone': '3434234'}

替换键-值对

d["telephon"] = 999999

d

{'name': 'Victor', 'age': 55, 'telephon': 999999, 'telephone': '3434234'}

删除某个键值所对应的项

d

{'name': 'Victor', 'age': 55, 'telephone': '3434234'}

检查是否包含某个键的项

"name" in d

True

"country" in d

False

x = []

x[42] = "Foobar"

---------------------------------------------------------------------------

IndexError Traceback (most recent call last)

in

1 x = []

----> 2 x[42] = "Foobar"

IndexError: list assignment index out of range

x[0] = "Foobar"

---------------------------------------------------------------------------

IndexError Traceback (most recent call last)

in

----> 1 x[0] = "Foobar"

IndexError: list assignment index out of range

x = [None] * 10

x

[None, None, None, None, None, None, None, None, None, None]

x[0] = "Foobar"

x

['Foobar', None, None, None, None, None, None, None, None, None]

x = {}

x[42] = "Foobar"

x

{42: 'Foobar'}

代码清单4-1 字典示例

# 字典示例

# 一个简单的数据库

# 将一个人名用作键的字典,每个人都用一个字典表示

# 字典包含键“phone”和“addr”,它们分别于电话号码和地址相关联

people = {

"Alice": {

"phone": "2341",

"addr": "Foo drive 23"

},

"Beth": {

"phone": "9102",

"addr": "Bar street 42"

},

"Cecil": {

"phone": "3158",

"addr": "Baz avenue 90"

}

}

# 电话号码和地址的描述性标签,供打印输出时使用

labels = {

"phone": "Phone Number",

"addr": "Address"

}

name = input("Name: ").capitalize()

# 要查找电话号码还是地址?

request = input("Phone Number (p) or Address (a)? ").lower()

# 使用正确的键:

if request == "p":

key = "phone"

if request == "a":

key = "addr"

# 仅当名字是字典包含的键时才打印信息:

if name in people:

print("{}'s {} is {}.".format(name, labels[key], people[name][key]))

Name: alice

Phone Number (p) or Address (a)? A

Alice's Address is Foo drive 23.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值