Python:Strings
来自KlniuWiki
(重定向自Python Strings)
String有以下特性:
- 不可改变
- 是一个从左到右的序列
- 支持连接、切片、索引、匹配等操作
目录 |
1 字符串常量
1.1 单双引号
有以下几种表示字面值的方法, 表示字符串时,单引号和双引号的作用是一样的,而且包围在引号内的字符串会自动连接起来
'spa"m' # Single quotes "spa'm" # Double quotes '''... spam ...''', """... spam ...""" # Triple quotes "s\tp\na\0m" # Escape sequences r"C:\new\test.spm" # Raw strings b'sp\x01am' # Byte strings in 3.0 title = "Meaning " 'of' " Life" # Implicit concatenation title # 'Meaning of Life'
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 (at most 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 16-bit hex |
| \Uhhhhhhhh | Unicode 32-bit hex |
| \other | Not an escape (keeps both \ and other) |
1.3 Raw Strings(抑制转义)
通过在字符串前加r或R,可以抑制字符串的转义,但是如果最后一个字符是\,则这个\还需要变为\\,即使字符串前面有r。
print(R'This\tis klniu.\n') # This\tis klniu.\n print(r'This\tis klniu.\n') # This\tis klniu.\n print('This\tis klniu.') # This is klniu. print(r'This\tis klniu.\') # 得到以下错误: ''' File "<interactive input>", line 1 print(r'This\tis klniu.\') ^ SyntaxError: EOL while scanning string literal ''' print(r'This\tis klniu.\\') # This\tis klniu.\\
1.4 块''''''
用三个引号(单双均可)包围起来的字符串,称为串,在这个字符串内,你可以包含多行数据,空格,制表符,等等,在写代码时,它可以注释大块的代码用以调试。
mantra = """Always look on the bright side of life.""" print(mantra)
上述代码将得到:
Always look
on the bright
side of life.
2 操作
String所支持的操作:
| Operation | Interpretation |
|---|---|
| S = '' | Empty string 空字符串 |
| S = "spam's" | Double quotes, same as single 双引号,和单引号相同 |
| S = 's\np\ta\x00m' | Escape sequences 转义序列 |
| S = """...""" | Triple-quoted block strings 三个单引号 |
| S = r'\temp\spam' | Raw strings 不转义字符串 |
| S = b'spam' | Byte strings in 3.0 (Chapter 36) 字节字符串 |
| S1 + S2 | Concatenate, 连接 |
| S * 3 | repeat 重复 |
| S[i] | Index 索引 |
| S[i:j] | slice 切片 |
| len(S) | length 长度 |
| "a %s parrot" % kind | String formatting expression 字符串格式化 |
| "a {0} parrot".format(kind) | String formatting method in 2.6 and 3.0 字符串格式化 |
| S.find('pa') | String method calls: search 搜索 |
| S.rstrip() | remove whitespace 移除空白字符 |
| S.replace('pa', 'xx') | replacement 替换 |
| S.split(',') | split on delimiter 用分隔符分隔 |
| S.isdigit() | content test 测试 |
| S.lower() | case conversion 大小写转换 |
| S.endswith('spam') | end test 尾部字符测试 |
| 'spam'.join(strlist) | delimiter join 合并 |
| S.encode('latin-1') | Unicode encoding, etc. Unicode编码 |
| for x in S: print(x) | Iteration 迭代 |
| 'spam' in S | membership 含有 |
| [c * 2 for c in S] | |
| map(ord, S) |
2.1 字符串连接与重复
可以用通过+把两个字符串连接起来生成一个新的字符串,也可以把一个字符串乘以一个整数得到整数个字符串连接的结果。
'abc' + 'def' # 'abcdef' '-' * 90 # 90 dashes,Repetition: like '-' + '-' + ...
2.2 迭代
可以通过for迭代的方法得到string的每个字符:
myjob = "hacker" for c in myjob: print(c, end=' ') # Step through items
2.3 查找
可以通过in来判断字符串内是否包含特定的字符串:
"k" in myjob # True, Found "z" in myjob # False, Not found 'spam' in 'abcspamdef' # True, Substring search, no position returned
2.4 索引和切片
因为string是序列化的,因此可以通过索引获取特定位置的字符。
另外可以通过给定一个区间,获得区间内的字符串,这就是切片,需要注意的是,切片包含第一个索引位置的字符,却并不包含最后一个位置字符。
索引(S[i])从偏移位置取得字符:
- 第一个字符在在偏移位置0处。
- 负值的索引表示从右向前搜索。
- S[0]表示取得第一个字符。
- S[-2]表示取得倒数第二个字符,和S[len(S)-2]等价。
切片(S[i:j])取得一个区间的字符串:
- 切片之后的结果并不包括区间右边边界位置的字符。
- 如果忽略边界值,切片将取0和字符串的长度为边界。
- S[1:3]取得偏移位置为1到偏移位置为3(但并不包含)区间的字符串。
- S[1:]取得偏移位置为1到字符串结尾区间的字符串。
- S[:3]取向从偏移位置0到偏移位置3(但不包含)区间的字符串。
- S[:-1]取得从偏移位置0到最后一个字符之间(但不包含)的字符串。
- S[:]取得从偏移位置0到字符串结尾区间的字符串,这也表示将拷贝整个字符串。
具体看代码:
S = 'spam' S[0], S[-2] # ('s', 'a'), Indexing from front or end S[1:3], S[1:], S[:-1], s[:] # ('pa', 'pam', 'spa', 'spam'), Slicing: extract a section
另外切片支持每隔特定的步长取得一个字符,步长默认为1,负的步长表示反转字符串:
S = 'abcdefghijklmnop' S[1:10:2] # 'bdfhj', 每隔2个字符取一个字符 S[::2] # 'acegikmo' S = 'hello' S[::-1] # 'olleh'
3 参考文献
- {{CiteGBM|主要责任者=Mark Lutz|题名=Learning Python, Fourth Edition|其他题名信息=|文献类型标志=M|其他