一、标示符和关键字Identifiers and Keywords
Python 有一个内置函数dir(),它用于返回一个对象的属性列表,该函数没有参数时返回Python的内置属性列表
>>> dir()
['__builtins__', '__doc__', '__name__']
__builtins__属性是一个模块,存储了Python的内置属性,可以把它设置为dir函数的参数
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError','AttributeError',...'sum', 'super', 'tuple', 'type', 'vars', 'zip']
二、整数类型
Python提供了两种内置的整数类型,int类型和bool类型,两者的转换与C语言相似。
1.整型Integers
>>> 14600926 # decimal
14600926
>>>0b110111101100101011011110 # binary
14600926
>>> 0o67545336 # octal
14600926
>>> 0xDECADE # hexadecimal
14600926
Table 2.2. Numeric Operators and Functions
Table 2.3. Integer Conversion Functions
Table 2.4. Integer Bitwise Operators
Python有两种Booleans类型对象:true和False
三、浮点数据类型
四、字符串类型Strings
1) Strings
text = """A triple quotedstring like this can include 'quotes' and
"quotes" without formality. Wecan also escape newlines \
so this particular string is actually onlytwo lines long."""
注意两者的区别,双引号中的双引号必须转义,单引号中的单引号必须转义
a = "Single 'quotes' are fine;\"doubles\" must be escaped."
b = 'Single \'quotes\' must be escaped; "doubles"are fine.'
Table 2.7. Python's String Escapes
若字符串str引用前面有r字符,则str保持字符串字面值,内部不转义。
ord(c)->integer
ord()函数返回包含一个字符的string类型的Unicode次序。
chr()函数与ord函数的作用相反,其参数是integer(0<=i<=0x10ffff),返回值是Unicode字符
>>> ascii(s)
"'anarchists are \u221e\u23b7'"
2) Comparing Strings
问题一、Unicode字符的表示方式并不唯一
import unicodedata
unicodedata.normlize(“NFKD”)
问题二、字符受限于特定的语言
3)Slicing and Striding Strings
[]是切片操作符(slice operator)
切片操作符有三种用法:
seq[start]
seq[start:end]
seq[start:end:step]
其中seq可以是任意的序列,例如list、string或tuple。
对于第二个函数而言,start和end可以为空,分别被默认为0和len(str);
操作符+或者+=用于字符串的连接,效率并不是特别高,可以利用方法str.join()函数;
对于第三个函数而言,start和end可以为空,但是要看步长,其符号决定方向。
5)String Operators and Methods
逆转:reversed()
复制>>> s = "=" * 5
>>> print(s)
=====
Table 2.8. String Methods #1
Table 2.9. String Methods #2
Table 2.10. String Methods #3
在python中编程,求子串在父串的起始位置有两个函数str.index()和str.find(),前者的代码更清晰,如下所示(左右两者的功能是一致的):
def extract_from_tag(tag, line): opener = "<" + tag + ">" closer = "</" + tag + ">" try: i = line.index(opener) start = i + len(opener) j = line.index(closer, start) return line[start:j] except ValueError: return None | def extract_from_tag(tag, line): opener = "<" + tag + ">" closer = "</" + tag + ">" i = line.find(opener) if i != -1: start = i + len(opener) j = line.find(closer, start) if j != -1: return line[start:j] return None |
str.count(), str.endswith(), str.find(), str.rfind(), str.index(),str.rindex()和str.startswith()这些函数都有两个可选参数,分别是开始位置和结束位置,示例如下:
s.count("m", 6) ==s[6:].count("m")
s.count("m", 5, -3) ==s[5:-3].count("m")
注意:is*()methods中的isdigit函数,其参数是基本的Unicode字符,所以str.isdigit()的参数是"\N{circled digit two}03" 返回的是True,所以即使str.isdigit()函数返回的是true,也不能确定其参数可以被转换成integer。
6)String Formatting with the str.format() Method
str.format()函数在把替换字段(replacement fields)置换成格式化参数,其示例:
>>> "The novel '{0}' waspublished in {1}".format("Hard Times", 1854)
"The novel 'Hard Times' was publishedin 1854"
在Python中连接string和number会引发TypeError错误,可以如以下的方式实现该功能
>>>"{0}{1}".format("The amount due is $", 200)
'The amount due is $200'
置换字段可以使用下面4种语法中的一种:
{field_name}
{field_name!conversion}
{field_name:format_specification}
{field_name!conversion:format_specification}
具体的用法可参考Programming in Python 3