python入门系列第六篇: 字符串

163 阅读5分钟
原文链接: zhuanlan.zhihu.com
字符串: 有序的字符的集合

python字符串属于不可变序列这一类型。


字符串常量
单引号: 'hello'
双引号: "hello"
三引号: """..."""
转义字符: "s\tp\na\0m"
raw字符: r"c:new\user\test/py"  # 'c:new\\user\\test/py'
byte字符串: b"sp\x"

关于单引号与双引号字符串, 两者是可以互换的, 另外两者都可以彼此嵌入。

>>> 's"hello'
's"hello'
>>> "s'hello"
"s'hello"
>>>

另外字符串合并的时候, 我们推荐使用+操作法明确表示这是一个合并操作。

>>> 'hello''world'
'helloworld'
>>> 'hello' + 'world'
'helloworld'
>>>


转义序列

通过反斜杠来引用特殊的字节编码称为转义序列

>>> s = 'a\nb\tc'
>>> print(s)
a
b	c
>>>

常见的字符串反斜杠字符

\newline 忽视
\\ 反斜杠, 保留\
\' 单引号
\" 双引号
\a 响铃
\b 倒退
\f 换页
\n 换行
\r 返回
\t 水平制表符
\v 垂直制表符
\xhh 十六进制
\ooo 八进制

如果我们想使用常量反斜杠, 可以使用"\\" 或者 row字符串.

>>> s = '\\'
>>> print(s)
\


raw字符串抑制转义

raw字符串: 以r开头, 处于字符串的第一个引号前面, 它会关闭转义机制。

>>> path = "c:\new\text.dat"
>>> print(path)
c:
ew	ext.dat

如果你想定义一个上述字符串的文件路径, 你会发现路径被转义了, 因此我们使用row字符串来处理。

>>> path = r"c:\new\text.dat"
>>> print(path)
c:\new\text.dat

或者使用反斜杠来消除转义。

>>> path = "c:\\new\\text.dat"
>>> print(path)
c:\new\text.dat
三重引号

三重引号格式: 以三重引号(单/双)开始, 后面跟随任意数量文本, 最后以三重引号结束。

"""
...

"""

三重引号常用于文档字符串, 多行注释。


字符串的常用操作
>>> a = 'hello'
>>> b = 'world'
>>> a + b
'helloworld'
>>> len(a)
5
>>> '*' * 4
'****'
>>> for x in a: print(x)
...
h
e
l
l
o
>>> 'o' in a
True

字符串的索引与切片

s:[i:j:k]
i: 下边界值(包括), 默认0
j: 上边界值(不包括), 默认字符串长度
k: 步进(默认0)
>>> s = 'hello'
>>> s
'hello'
>>> s[0], s[1:3]
('h', 'el')
>>> s[:]
'hello'
>>> s[:-1]
'hell'
>>> s[:-1] + s[-1]
'hello'
>>> s[::2]
'hlo'
>>>
>>> s[::-1]
'olleh'
>>>

字符串属于不可变序列, 因此你无法在原地修改字符串。


字符串方法


Python字符串方法大全www.jianshu.com


修改字符串

字符串本身是属于不可变类型, 我们想要修改字符串只能通过创建一个新的字符串。


>>> s = 'hello world'
>>> s = s[:6] + ' add ' + s[6:]
>>> s
'hello  add world'


>>> s = 'hello world'
>>> s = s.replace(' ', ' add ')
>>> s
'hello add world'


>>> s = 'hello world'
>>> l = list(s)
>>> l
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> l[6:] = 'kobe'
>>> l
['h', 'e', 'l', 'l', 'o', ' ', 'k', 'o', 'b', 'e']
>>> s = ''.join(l)
>>> s
'hello kobe'
>>>


字符串格式化表达式

格式化字符串: 总是返回新的字符串

1. 在%操作符左边放置一个需要进行格式化的字符串,这个字符串带有一个或者多个嵌入的转换目标, 都以%开头。
2. 在%操作符右边放置一个(或者多个, 嵌入到元组)对象,这些对象会对应插入到左侧对应的转换目标中。


>>> 'my name is %s, and age is %d' %('kobe', 30)
'my name is kobe, and age is 30'
>>> 'i have %f $'%3121212.23
'i have 3121212.230000 $'

常见的字符串格式化代码:

s 字符串
c 字符
d 十进制整数
i 整数
o 八进位整数
x 十六进位整数
X 大写等同x
e 浮点指数
E 大写 等同与e
f 浮点十进制
F 大写, 等同于f
g 浮点e/f
G 浮点E/f
% 常量


在%和字符码之间, 我们可以放置一个字典的键: 罗列出左对齐(-), 正负号(+), 补零(0)的标示位. 或者可以给出数字的整体长度和小数点后的位数。


>>> int1 = 1234
>>> s = 'int: ...%d...%-6d...%06d'%(int1, int1, int1)
>>> s
'int: ...1234...1234  ...001234'

另外%e, %f, %g对浮点数表示方法也不同

>>> x = 3.1514926
>>> '%e | %f | %g' %(x, x, x)
'3.151493e+00 | 3.151493 | 3.15149'
>>> '%-6.2f | %05.2f | %+06.1f' % (x, x, x)
'3.15   | 03.15 | +003.2'

如果我们只在运行时候才知道大小, 我们可以在格式化时候通过*来指定通过计算得出width和precision.

>>> '%f, %.2f, %.*f'%(1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33, 0.3333'

基于字典的字符串格式化。

>>> 'my name is %(name)s, and age is %(age)d' %({'name': 'kobe', 'age': 30})
'my name is kobe, and age is 30'


基于字符串的format方法: 使用主体字符串作为模版, 可以接受{位置}或者{关键字}的形式接受任意多个替换的值的参数.

>>> 'my name is {0}, and age is {1}'.format('kobe', 20)
'my name is kobe, and age is 20'
>>> 'my name is {name}, and age is {age}'.format(age=30, name='kobe')
'my name is kobe, and age is 30'
>>> 'my name is {name}, and age is {0}'.format(30, name='kobe')
'my name is kobe, and age is 30'

基于f-string来格式话字符串, 类似js的模版字符串, 以f开头, 后面跟随一个允许插入变量的字符串。

>>> name = 'kobe'
>>> age = 30
>>> s = f'my name is {name}, and age is {age}'
>>> s
'my name is kobe, and age is 30'