读书笔记:LearningPython第五版 (第七章 字符串基础)

重点

  1. 对string的多次操作,不如先变成list,再join回去性能更好
  2. 两种formatting的大致使用: 表达式方式也可以设置keyword,传字典; format方式可以引用[]和.

Chap7 字符串基础

Python中字符串有3种类型:

  1. str:处理unicode
  2. bytes:处理二进制
  3. bytearray:bytes的mutable版本

7.1 String字面值

表示含义
S = “”"…multiline…"""Triple-quoted block strings
S = r’\temp\spam’ Raw strings (no escapes)
B = b’sp\xc4m’Byte strings in 2.6, 2.7, and 3.X (Chapter 4, Chapter 37)
U = u’sp\u00c4m’Unicode strings in 2.X and 3.3+ (Chapter 4, Chapter 37)

7.1.1 python会自动拼接连续字符串

>>> title = "Meaning " 'of' " Life" # Implicit concatenation
>>> title
'Meaning of Life'

7.1.2 转义字符

EscapeMeaning
\newline Ignored (continuation line)
\Backslash (stores one )
Single quote (stores ')
"Double quote (stores ")
\aBell
\bBackspace
\fFormfeed
\nNewline (linefeed)
\rCarriage return
\tHorizontal tab
\vVertical tab
\xhhCharacter with hex value hh (exactly 2 digits)
\oooCharacter with octal value ooo (up to 3 digits)
\0Null: binary 0 character (doesn’t end string)
\N{ id }Unicode database ID
\uhhhhUnicode character with 16-bit hex value
\UhhhhhhhhUnicode character with 32-bit hex valuea
\otherNot an escape (keeps both \ and other)
  1. Python内 \0并不会终结字符串。事实上,没有字符会终结字符串
  2. 如果Python不认识某个转义字符,那它会直接输出\和这个字符

7.1.3 raw string

r的字符串是raw string, 会关闭\的转义含义。但是对于 '"\还是会转义它。

>>> path = r'C:\new\text.dat'
>>> path # Show as Python code
'C:\\new\\text.dat'

Python在Windows内的路径解析时,也会理解前slash: C:/new/text.dat

7.2 Strings in Action

>>> ord('s')     # 将字符串转换成Unicode的 code point 数字
115      
>>> chr(115)   # 将Unicode 的 code point数字转换成 字符串
's'
表达式作用
S1+S2拼接
S1 *3重复
S[i]索引
S[i:j]切片
len(S)求长度
“a %s parrot” % kind格式化
“a {0} parrot”.format(kind)格式化
S.find(‘pa’)查找
S.strip()去掉空
S.replace(‘old’,‘new’)替换
S.split(’’)切割
S.isdigit()判断数字
S.lower()转换小写
S.endswith(‘spam’)判断结尾
‘spam’.join(strlist)连接
S.encode(‘latin-1’)编码
B.decode(‘utf8’)解码
‘spam’ in S判断存在

负索引实际上是 加上了长度之和

7.3 String的方法

7.3.1 Method Call

object.method(arguments)

方法调用实际上是2个步骤的总和:

  1. 属性获取(attributes fetch): object.member获取 member这个属性
  2. 调用表达式:function(arguments)调用了这个function的代码,并且传入参数,接收返回值

Python在执行object.method(arguments)时,会先获取 object的method方法,然后将objectarguments当作参数传入。

7.3.2 string 的methods

S.replace(old, new [, count])
S.find(sub [, start [, end]])
S.split([sep [,maxsplit]])
S.join(iterable)

如果需要对很长的String做一系列操作,与其每次都生成一个新的string然后返回,不如先将string转换成list,再做in-place操作,这样能提高性能。之后将list再join回来,性能也要比拼接多个字符串更好

最早的string方法是使用string模块内的函数调用,然后在Python3内已经移除了,但是string模块内还有其他的string工具

7.4 String Formatting Expression

7.4.1 格式

# String formatting expressions: 
'...%s...' % (values)
%[(keyname)][flags][width][.precision]typecode
  • flag: +代表符号; -代表左对齐; 0 代表用0填充前
CodeMeaning
sString (or any object’s str(X) string)
rSame as s, but uses repr, not str
cCharacter (int or str)
dDecimal (base-10 integer)
iInteger
uSame as d (obsolete: no longer unsigned)
oOctal integer (base 8)
xHex integer (base 16)
XSame as x, but with uppercase letters
eFloating point with exponent, lowercase
ESame as e, but uses uppercase letters
fFloating-point decimal
FSame as f, but uses uppercase letters
gFloating-point e or f
GFloating-point E or F
%Literal % (coded as %%)

7.4.2 使用

a. 给tuple
#注: width和precision都可以写成*,然后在后面传入参数
>>> '%f, %.2f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33, 0.3333'

>>> '%s is a %s'%(name, animal)
>>> 'Jason is a man'
b. 传字典
>>> '%(qty)d more %(food)s' % {'qty': 1, 'food': 'spam'}
'1 more spam'
# var() 内置函数,能将当前环境存在的变量,以字典的方式返回:
>>> food = 'spam'
>>> qty = 10
>>> vars()
{'food': 'spam', 'qty': 10, ...plus built-in names set by Python... }

>>> '%(qty)d more %(food)s' % vars()

var内置函数

7.5 String Formatting Method Call

Python3出来的,来自.NET
{}内可以写:{1},{name},{}

#String formatting method calls: 
'...{}...'.format(values)

7.5.1 使用

a.混合 {0} {name}
>>> template = '{motto}, {0} and {food}' # By both
>>> template.format('ham', motto='spam', food='eggs')
'spam, ham and eggs'

b. 使用内部的成员

>>> 'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'laptop'})
'My laptop runs win32'
>>> 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'laptop'})
'My laptop runs win32'

7.5.2 高级使用

{fieldname component !conversionflag :formatspec}

  • fieldname: 可选的,就是之前的 {0} 或者 {name} 来表示具体参数位置
  • component:就是上面 “.name” or “[index]”来获取成员
  • conversionflag:以!开头,后面接r, s or a来调用repr, str, ascii 内置函数
  • formatspec:以:开头,用来表示格式化方式,比如field width, alignment, padding, decimal precision, and so on

format的具体格式:
[[fill]align][sign][#][0][width][,][.precision][typecode]

  • fill can be any fill character other than { or };
  • align may be <, >, =, or ^, for left alignment, right alignment, padding after a sign character, or centered alignment, respectively;
  • sign may be +, −, or space;
  • and the , (comma) option requests a comma for a thousands separator as of Python 2.7 and 3.1.
  • width and precision are much as in the % expression, and the formatspec may also contain nested {} format strings with field names only, to take values from the arguments list dynamically
  • typecode:基本和之前的 %d… 一样,但是多了一个 %b来表示二进制

其他

  1. 单一对象可以使用内置函数format(object , formatspec)
  2. 自定义对象可以定义__format__

7.6 General Type Categories

Python内三个大类型:

Numbers (integer, floating-point, decimal, fraction, others)
Support addition, multiplication, etc.
Sequences (strings, lists, tuples)
Support indexing, slicing, concatenation, etc.
Mappings (dictionaries)
Support indexing by key, etc

根据是否可变:

Immutables (numbers, strings, tuples, frozensets)
不支持in-place 改变,只能通过操作来创建一个新的对象并返回
Mutables (lists, dictionaries, sets, bytearray)
可以in-place改变,而不需要创建新对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值