Learning.Python.3rd.Edition 笔记[5:7]

The Dynamic Typing Interlude
a = 3的后台操作过程
1. 创建一个对象,将值设置为3.
2. 如果a不存在,则创建一个变量
3. 将变量a指向值为3的这个对象

变量与对象 存放在不同的内置位置,一个变量只会指向一个对象,而不会指向一个对象

连接对象和变量之间的link,被称为引用 references

Python中,对象本身包含了类型信息,所以变量无须声明类型

GC garbage collection.

当一个对象不被变量引用时,将会被GC回收

Python中对于对象的引用关系,与Java基本一致,不过特殊的有:

1:list对象的变量中使用 [:]方法,可以获取一个拷贝
2:字典对象,可以使用 object.copy方法进行对象拷贝
3:其他对象,可以使用copy模块进行拷贝操作,比Java丰富的多

==运算符,在非字符串与intger对象时,比较对象值是否相同,is用于比较对象是否指向同一个对象

本章主要介绍的还是关于对象,变量,引用之间的关系,和Java类似,在于一些关键字和方法的使用,具体以后
可以再了解下,避免语句理解的错误


CHAPTER 7
string 字符串

Python中的字符串类型,与C中类似,由字符数组组成的序列,不过功能更丰富一些,而且需要注意string
是不可修改的,在Python中,string也是属于sequence的一种,提供了类似List和tuples类似的方法

string声明中,可以使用"双或'单引号

常见的String操作

Operation Interpretation
s1 = '' Empty string
s2 = "spam's" Double quotes
block = """...""" Triple-quoted blocks
s3 = r'\temp\spam' Raw strings
s4 = u'spam' Unicode strings
s1 + s2
s2 * 3 Concatenate, repeat
s2[i] Index, slice, length
s2[i:j]
len(s2)
"a %s parrot" % type String formatting
s2.find('pa') String method calls: search, remove whitespace, replacement, split on

s2.rstrip( ) delimiter,content test, case conversion, etc.
s2.replace('pa', 'xx')
s1.split(',')
s1.isdigit( )
s1.lower( )

for x in s2
'spam' in s2

还有其他的包括 正则表达式模块 re (regular expression)

Python会自动对两个同时声明的字符串进行拼接,如:title = "Meaning " 'of' " Life"
如果声明时,使用逗号,那么将会创建一个元组tuple,如:c='dafa','awwi'

与Java相同,提供\用于在字符串中提供转义功能

常见的转义表
Escape Meaning
\n ewline Ignored (continuation)
\\ Backslash (keeps a \)
\' Single quote (keeps ')
\" Double quote (keeps ")
\a Bell
\b Backspace
\f Formfeed
\n Newline (linefeed)
\r Carriage return
\t Horizontal tab
\v Vertical tab
\N{id} Unicode database ID
\uhhhh Unicode 16-bit hex
\Uhhhh... Unicode 32-bit hexa
\xhh Hex digits value
\ooo Octal digits value
\0 Null (doesn’t end string)
\other Not an escape (kept)

其中特别的有: \0常用于生成二进制流格式,如s = '\001\002\x03' ,使用len()统计长度时,将返回3

Raw Strings 在字符串之前加入r'',用于过滤\,既关闭转义功能
尤其在打开文件时,需要使用\\转义成一个\,或者使用r代替,使用r更有利于阅读,而外在跨平台情况
下,效果更好

''' 三个引号(单双均可) 用于声明多行字符串,多用于xml,HTML等格式化显示,也常用于docString

可以使用U来声明 Unicode字符串.

在Python中,将会有一种新的类型bytes,用于表示可变的字符序列,同时string(str)默认类型就为Unicode

Strings in Action

基础操作 Basic Operations

+ 与Java相同,用于字符串的拼接
* 与Java不同,可以生成N个同内容字符串的拼接

与C相同,字符串可以使用索引进行访问,索引由0开始,Python支持使用负数索引访问元素,如 -1表示最后一位元素
同时支持使用[:]的切片形式获取指定索引区间的字符串内容
注意出现[0:4]时,得到是0开始,到4之前的元素,不过似乎也可以理解成包括0在内的4个元素,因为第二个参数可以
为负数,所以还是按照第一种理解比较好

三参数切片 [::] 带两个冒号的切片获取方式,前两个参数意义相同,最后一个代表跳过的步骤,在指定区间,按照一定的
步数进行选择
a="1234567890"
print a[0:5:2] //将返回135.

同样也可以使用负数进行反向选择 S[5:1:-1]
切片可以用于去除文件读取中的\n符,[:-1]
也可以用于修改字符串,使用切片后进行+号拼接

不能直接将str和int进行相加操作,需要进行转换后才可以,同理float也需要转换

转换方式常用的有 str() 与repr()方法

字符转换,将数字转换成对于的字符,或从数字转换成对应的字符 ,注意需要是ASCII的范围内
ord('s') 与 chr(115) 等方法

因为字符串本身是不可修改的,所以对字符串的修改,都会创建一个新的对象

也常用% 进行字符串的格式化,类似C的 printf方法,以及Java6中提供的System.out.printf方法
"%d %s %d you" % (1, 'spam', 4)
其中注意 右边的参数需要放置在一个tuple中(一个参数时就非必须),可以使用%s,代表一个List
,因为都将会被转换成一个字符串的形式

高级字符串格式化
Code Meaning
%s String (or any object)
%r s, but uses repr, not str
%c Character
%d Decimal (integer)
%i Integer
%u Unsigned (integer)
%o Octal integer
%x Hex integer
%X x, but prints uppercase
%e Floating-point exponent
%E e, but prints uppercase
%f Floating-point decimal
%g Floating-point e or f
%G Floating-point E or f
%% Literal %

其中在 %之后,可以带上各种不同的参数,具体格式如下
%[(name)][flags][width][.precision]code

功能很丰富,书中的例子介绍不多,需要专门的写一篇进行详细介绍

也可以使用字典的方式进行格式化赋值操作
"%(n)d %(x)s" % {"n":1, "x":"spam"}
'1 spam'

list(str) 方法,可以将字符串转换成List

Python中的String提供了许多和Java类似的方法,就是更多一些

Python中三种主要的类型

Numbers
Support addition, multiplication, etc. 支持加法,乘法等

Sequences
Support indexing, slicing, concatenation, etc. 支持索引,切片,关联

Mappings
Support indexing by key, etc 支持key索引

序列中通用的计算方法(list,tuple,strings)
X + Y makes a new sequence object with the contents of both operands.
X * N makes a new sequence object with N copies of the sequence operand X.

方法调用包括两种不同的方式
y = string.replace(S, '+', 'spam')
x = S.replace('+', 'spam')
其中第一种用的机会感觉并不多,所有没有深入了解

照旧凑字数

Chapter Quiz
1. Can the string find method be used to search a list?

2. Can a string slice expression be used on a list?

3. How would you convert a character to its ASCII integer code? How would you
convert the other way, from an integer to a character?

4. How might you go about changing a string in Python?

5. Given a string S with the value "s,pa,m", name two ways to extract the two charactersin the middle.

6. How many characters are there in the string "a\nb\x1f\000d"?

7. Why might you use the string module instead of string method calls?

Quiz Answers

1. No, because methods are always type-specific; that is, they only work on a single data type. Expressions are generic, though, and may work on a variety of
types. In this case, for instance, the in membership expression has a similar
effect, and can be used to search both strings and lists.

2. Yes. Unlike methods, expressions are generic, and apply to many types. In this
case, the slice expression is really a sequence operation—it works on any type of
sequence object, including strings, lists, and tuples. The only difference is that
when you slice a list, you get back a new list.

3. The built-in ord(S) function converts from a one-character string to an integer
character code; chr(I) converts from the integer code back to a string.

4. Strings cannot be changed; they are immutable. However, you can achieve a
similar effect by creating a new string—by concatenating, slicing, running formatting expressions, or using a method call like replace—and then assigning the result back to the original variable name.

5. You can slice the string using S[2:4], or split on the comma and index the string using S.split(',')[1]. Try these interactively to see for yourself.

6. Six. The string "a\nb\x1f\000d" contains the bytes a, newline (\n), b, binary 31 (a hex escape \x1f), binary 0 (an octal escape \000), and d. Pass the string to the built-in len function to verify this, and print each of its characters’ ord results to see the actual byte values. See Table 7-2 for more details.

7. You should never use the string module instead of string object method calls
today—it’s deprecated, and its calls are slated for removal in Python 3.0. The
only reason for using the string module at all is for its other tools, such as predefined constants, and advanced template objects.
Learning Python, 3rd Edition Mark Lutz Book Description Publication Date: October 29, 2007 | ISBN-10: 0596513984 | ISBN-13: 978-0596513986 | Edition: Third Edition Portable, powerful, and a breeze to use, Python is ideal for both standalone programs and scripting applications. With this hands-on book, you can master the fundamentals of the core Python language quickly and efficiently, whether you're new to programming or just new to Python. Once you finish, you will know enough about the language to use it in any application domain you choose. Learning Python is based on material from author Mark Lutz's popular training courses, which he's taught over the past decade. Each chapter is a self-contained lesson that helps you thoroughly understand a key component of Python before you continue. Along with plenty of annotated examples, illustrations, and chapter summaries, every chapter also contains Brain Builder, a unique section with practical exercises and review quizzes that let you practice new skills and test your understanding as you go. This book covers: Types and Operations -- Python's major built-in object types in depth: numbers, lists, dictionaries, and more Statements and Syntax -- the code you type to create and process objects in Python, along with Python's general syntax model Functions -- Python's basic procedural tool for structuring and reusing code Modules -- packages of statements, functions, and other tools organized into larger components Classes and OOP -- Python's optional object-oriented programming tool for structuring code for customization and reuse Exceptions and Tools -- exception handling model and statements, plus a look at development tools for writing larger programs. Learning Python gives you a deep and complete understanding of the language that will help you comprehend any application-level examples of Python that you later encounter. If you're ready to discover what Google and YouTube see in Python, this book is the best way to get started.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值