日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2024/7/23 python 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 467python教程_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.

總結

以上是生活随笔為你收集整理的467python教程_Magnus Lie Hetland的《Python基础教程(第3版)》自学笔记(持续更新中)...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。