文章目录
Python 05-字符串
在 Python 中处理文本数据是使用 str
对象,也称为 字符串。 字符串是由 Unicode 码位构成的不可变 序列。 字符串字面值有多种不同的写法:
- 单引号:
'允许包含有 "双" 引号'
- 双引号:
"允许包含有 '单' 引号"
。 - 三重引号:
'''三重单引号'''
,"""三重双引号"""
使用三重引号的字符串可以跨越多行 —— 其中所有的空白字符都将包含在该字符串字面值中。
1、 字符串字面值
- 由空格分隔的多个字符串字面值会被隐式地转换为单个字符串字面值。 也就是说,
("spam " "eggs") == "spam eggs"
。 - 使用前缀
'b'
或'B'
;它们生成bytes
类型而非str
类型的实例。它们只能包含 ASCII 字符;字节对应数值在128及以上必须以转义形式来表示。 - 使用前缀
'r'
或'R'
;这种字符串被称为 原始字符串 ,其中的反斜杠会被当作其本身的字面字符来处理。 - 使用前缀
'f'
或'F'
前缀的字符串字面值称为 格式化字符串字面值。'f'
可与'r'
连用,但不能与'b'
或'u'
连用,因此存在原始格式化字符串,但不存在格式化字节串字面值
2、转义字符
注意:python是没有字符这种类型的
可用的转义序列如下:
转义序列 | 含义 | 注释 |
---|---|---|
\newline | 反斜杠加换行全被忽略 | |
\\ | 反斜杠 (\ ) | |
\' | 单引号 (' ) | |
\" | 双引号 (" ) | |
\a | ASCII 响铃 (BEL) | |
\b | ASCII 退格 (BS) | |
\f | ASCII 进纸 (FF) | |
\n | ASCII 换行 (LF) | |
\r | ASCII 回车 (CR) | |
\t | ASCII 水平制表 (TAB) | |
\v | ASCII 垂直制表 (VT) | |
\ooo | 八进制数 ooo 码位的字符 | 最多三个八进制数 |
\xhh | 十六进制数 hh 码位的字符 | 必须为两个十六进制数 |
仅在字符串字面值中可用的转义序列如下:
转义序列 | 含义 | 注释 |
---|---|---|
\N{name} | Unicode 数据库中名称为 name 的字符 | |
\uxxxx | 16位十六进制数 xxxx 码位的字符 | 必须为四个十六进制数 |
\Uxxxxxxxx | 32位16进制数 xxxxxxxx 码位的字符必须为八个十六进制数 |
3、字符串的相关方法
3.1 字符串的拼接
-
三重引号:"""…""" 或 ‘’’…’’’。字符串中的回车换行会自动包含到字符串中
>>> str = """hello ... world""" >>> print(str) hello world
如果不想包含,在行尾添加一个 \ 即可。
>>> str = """ hello \ ... world""" >>> print(str) hello world
-
使用
+
进行连接(粘到一起)
连接变量 也使用 +>>> 'hello' + 'world' 'helloworld'
-
也可以用
*
进行重复:>>> 'hello '*3 'hello hello hello '
-
相邻的两个或多个 字符串字面值 会自动连接
>>> 'hello ' 'world' 'hello world'
3.2 不可变序列的方法
str 本身是不可变序列,所以可以使用一些通用的方法
-
通用序列操作。
运算 s =“1234567890” t = “abbcccdddd” 注释 x in s
x = ‘0’ --> True; x = ‘a’ --> False; x not in s
x = ‘0’ --> False; x = ‘a’ --> True; s + t
s 与 t 相拼接 s * n
或n * s
相当于 s 与自身进行 n 次拼接 s[i]
索引从左到右:0~n-1
索引从右到左:-1~-ns[i:j]
s 从 i 到 j 的切片,s[2:3] = “23” s[i:j:k]
s 从 i 到 j 步长为 k 的切片 s[1:3:2] = “1” len(s)
s 的长度 10 min(s)
s 的最小项 ‘0’ max(s)
s 的最大项 ‘9’ s.index(x[, i[, j]])
x 在 s 中首次出现项的索引号(索引号在 i 或其后且在 j 之前)
s.index(1,0,10) = 1s.count(x)
x 在 s 中出现的总次数, 统计
3.3 切片
字符串的切片用的比较多,从序列中抽出来学习,通过索引实现切片功能,切片的开始总是被包括在结果中,而结束不被包括。
-
索引 --支持下标,支持负数
# 长度 5 的字符串 >>> s = "01234" # 正向索引 【0~4】 >>> s[0] '0' >>> s[4] '4' # 正向索引 【-1~ -5】 >>> s[-1] '4' >>> s[-5] '0'
-
切片表示法
>>> s = "01234" >>> s[2:4] '23' >>> s[-1:-3] '' >>> s[-3:-1] '23'
-
切片的索引有默认值;省略开始索引时默认为0,省略结束索引时默认为到字符串的结束
>>> s = "01234" >>> s[:3] # s[0:3] '012' >>> s[3:0] # s[3:4] '34'
3.4 字符串函数
函数 | 功能 | |
---|---|---|
str.capitalize () | 返回字符串的副本,其首个字符大写,其余为小写 | >>> “hello world!”.capitalize() ‘Hello world!’ |
str.casefold () | 返回原字符串消除大小写的副本 | >>> “helLo World”.casefold() ‘hello world’ |
str.count(sub[, start[, end]]) | 子字符串 sub 在 [start, end] 范围内非重叠出现的次数。 | |
str.encode (encoding=“utf-8”, errors=“strict”) | 返回原字符串编码为字节串对象的版本 | >>> “hello”.encode() b’hello’ |
str.expandtabs (tabsize=8) | 返回字符串的副本,其中所有的制表符会由一个或多个空格替换 | |
str.find (sub[, start[, end]]) | 返回子字符串 sub 在 s[start:end] 切片内被找到的最小索引。 | |
str.index (sub[, start[, end]]) | ||
str.startswith(prefix[, start[, end]]) | ||
str.endswith (suffix[, start[, end]]) | 字符串是否以 suffix 结束 | |
str.format (*args, **kwargs) | 执行字符串格式化操作。 | 见格式化部分 |
str.format_map (**mapping) | ||
str.join(iterable) | ||
str.lower() | ||
static str.maketrans(x[, y[, z]]) | ||
str.partition(sep) | ||
str.replace(old, new[, count]) | ||
str.split(sep=None, maxsplit=-1) | ||
str.splitlines([keepends]) | ||
str.strip([chars]) | ||
str.zfill(width) |
4、格式化字符串
4.1、格式化字符串字面值
格式化字符串字面值 或称 f-string 是带有 'f'
或 'F'
前缀的字符串字面值。
这种字符串可包含替换字段,即以 {}
标示的表达式部分。
-
默认使用
>>> year = 2000 >>> f = f'This year is: {year}' >>> print(f)This year is: 2000
-
嵌套使用
顶层的格式说明符可以包含有嵌套的替换字段。这些嵌套字段也可以包含有自己的转换字段和 格式说明符,但不可再包含更深层嵌套的替换字段。这里的 格式说明符微型语言 与字符串 .format() 方法所使用的相同。>>> width = 10 >>> precision = 4 >>> value = decimal.Decimal("12.34567") >>> f"result: {value:{width}.{precision}}" # nested fields'result: 12.35'
-
包含 ‘=’ 符号 , 输出表达式
在提供了等于号 ‘=’ 的时候,输出将包含表达式文本,’=’ 以及求值结果。 左花括号 ‘{’ 之后包含在表达式中及 ‘=’ 后的空格将在输出时被保留。>>> year = 2000 >>> f'{year = }''year = 2000'
-
以冒号 ‘:’ 标示的格式说明符
>>> from datetime import date >>> today = date(2000,1,1) >>> f"{today:%B %d, %y}"'January 01, 00'
-
替换字段的语法:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"field_name ::= arg_name ("." attribute_name | "[" element_index "]")*arg_name ::= [identifier | digit+]attribute_name ::= identifierelement_index ::= digit+ | index_stringindex_string ::= <any source character except "]"> +conversion ::= "r" | "s" | "a"format_spec ::= <described in the next section>
replacement_field 替换字段开头可以用一个 field_name 指定要对值进行格式化并取代替换字符被插入到输出结果的对象。 field_name 之后有可选的 感叹号 ‘!’ 加 conversion 字段,以及 一个冒号 ‘:’ 加 format_spec字段组成。
4.2、str.format()
-
标准格式说明符 的一般形式如下:
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]fill ::= <any character>align ::= "<" | ">" | "=" | "^"sign ::= "+" | "-" | " "width ::= digit+grouping_option ::= "_" | ","precision ::= digit+type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
'#'
选项可以让“替代形式”被用于转换。 替代形式会针对不同类型分别定义。 此选项仅对整数、浮点数和复数类型有效。 对于整数类型,当使用二进制、八进制或十六进制输出时,此选项会为输出值分别添加相应的'0b'
,'0o'
, or'0x'
前缀。 -
按位置访问参数:
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c')'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # 解包:unpacking argument sequence'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated'abracadabra'
-
按名称访问参数:
>>> "Point:{x},{y}".format(x="20", y="30")'Point:20,30'
-
访问参数的属性:
>>> c = 1 + 2j >>> "complex {0} : {0.real} {0.imag}".format(c)'complex (1+2j) : 1.0 2.0'
-
访问参数的项:
>>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)'X: 3; Y: 5'
-
替代 %s 和 %r:
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')"repr() shows quotes: 'test1'; str() doesn't: test2"
-
对齐文本以及指定宽度
>>> '{:<30}'.format('left aligned')'left aligned ' >>> '{:>30}'.format('right aligned')' right aligned' >>> '{:^30}'.format('centered')' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char'***********centered***********'
-
替代 %x 和 %o 以及转换基于不同进位制的值:
>>> # format also supports binary numbers >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)'int: 42; hex: 2a; oct: 52; bin: 101010' >>> # with 0x, 0o, or 0b as prefix: >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
-
使用逗号作为千位分隔符:
>>> '{:,}'.format(1234567890)'1,234,567,890'
-
表示为百分数:
>>> points = 19 >>> total = 22 >>> 'Correct answers: {:.2%}'.format(points/total) 'Correct answers: 86.36%'
-
使用特定类型的专属格式化:
>>> import datetime >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58) >>> '{:%Y-%m-%d %H:%M:%S}'.format(d) '2010-07-04 12:15:58'
4.3、printf 风格的字符串格式化
不详细解释了,可以参看文档
print('%(language)s has %(number)03d quote types.' %
{'language': "Python", "number": 2})
Python has 002 quote types.