读书笔记:LearningPython第五版 (第七章 字符串基础)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了读书笔记:LearningPython第五版 (第七章 字符串基础),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6503字,纯文字阅读大概需要10分钟。
内容图文
![读书笔记:LearningPython第五版 (第七章 字符串基础)](/upload/InfoBanner/zyjiaocheng/856/e08abf60e29f437b8d74940fa742323a.jpg)
目录
重点
- 对string的多次操作,不如先变成list,再join回去性能更好
- 两种formatting的大致使用: 表达式方式也可以设置keyword,传字典; format方式可以引用[]和.
Chap7 字符串基础
Python中字符串有3种类型:
str
:处理unicodebytes
:处理二进制bytearray
:bytes的mutable版本
7.1 String字面值
表示 | 含义 |
---|---|
S = “”"…multiline…""" | Triple-quoted block strings |
S = r’\temp\spam’ R | aw 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 转义字符
Escape | Meaning |
---|---|
\ | newline Ignored (continuation line) |
\ | Backslash (stores one ) |
’ | Single quote (stores ') |
" | Double quote (stores ") |
\a | Bell |
\b | Backspace |
\f | Formfeed |
\n | Newline (linefeed) |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\xhh | Character with hex value hh (exactly 2 digits) |
\ooo | Character with octal value ooo (up to 3 digits) |
\0 | Null: binary 0 character (doesn’t end string) |
\N{ id } | Unicode database ID |
\uhhhh | Unicode character with 16-bit hex value |
\Uhhhhhhhh | Unicode character with 32-bit hex valuea |
\other | Not an escape (keeps both \ and other) |
- Python内
\0
并不会终结字符串。事实上,没有字符会终结字符串 - 如果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个步骤的总和:
- 属性获取(attributes fetch):
object.member
获取 member这个属性 - 调用表达式:
function(arguments)
调用了这个function的代码,并且传入参数,接收返回值
Python在执行object.method(arguments)
时,会先获取 object的method方法,然后将object
和arguments
当作参数传入。
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填充前
Code | Meaning |
---|---|
s | String (or any object’s str(X) string) |
r | Same as s, but uses repr, not str |
c | Character (int or str) |
d | Decimal (base-10 integer) |
i | Integer |
u | Same as d (obsolete: no longer unsigned) |
o | Octal integer (base 8) |
x | Hex integer (base 16) |
X | Same as x, but with uppercase letters |
e | Floating point with exponent, lowercase |
E | Same as e, but uses uppercase letters |
f | Floating-point decimal |
F | Same as f, but uses uppercase letters |
g | Floating-point e or f |
G | Floating-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
来表示二进制
其他:
- 单一对象可以使用内置函数
format(object , formatspec)
- 自定义对象可以定义
__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改变,而不需要创建新对象
内容总结
以上是互联网集市为您收集整理的读书笔记:LearningPython第五版 (第七章 字符串基础)全部内容,希望文章能够帮你解决读书笔记:LearningPython第五版 (第七章 字符串基础)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。