字符串(String),是由零个或多个字符组成的有限序列,在 Python 中表示文本的数据类型。
字符只是一个符号,例如:字母(A-Z)、数字(0-9)、特殊符号(~!@#¥%…)等。
| 版权声明:一去、二三里,未经博主允许不得转载。
在 Python 中,字符串由内置的 str 类型定义。
>>> s = 'Hello, Python!'
>>> type(s)
<class 'str'>
可以使用单引号(''
)或双引号(""
)来表示字符串。
PS: 单引号比双引号更常用。
>>> s = 'Hello' # 单引号
>>> s
'Hello'
>>>
>>> s = "Hello" # 双引号
>>> s
'Hello'
字符串可以跨多行,但是每行末尾必须添加反斜杠(\
)以转义换行符。
>>> s = 'Hello \
... World'
>>> s
'Hello World'
三重引号('''
或 """
)内的字符串可以跨多个文本行。
# 三重单引号
>>> s = '''Hello
... Python'''
>>> s
'Hello\nPython'
>>>
# 三重双引号
>>> s = """
... Hello
... Python
... """
>>> s
'\nHello\nPython\n'
注意: 三重引号通常用于表示多行字符串和 docstring。
字符串是字符的有序序列,可以通过其位置来获取具体的字符。在 Python 中,位置有一个优雅的称呼 - 索引(index)。
索引分为两种形式:
其中,length 为字符串的长度。
为了更清晰以上概念,来看一个直观地索引图。假设,有一个字符串 s = "Hello"
:
使用 [index]
的语法形式来访问指定索引处的字符:
>>> s = 'Hello'
>>>
>>> s[0] # 第一个字符
'H'
>>>
>>> s[4] # 最后一个字符
'o'
负索引(反向索引)从字符串的末尾开始计数,也可以起到同样的效果:
>>> s[-5] # 第一个字符
'H'
>>>
>>> s[-1] # 最后一个字符
'o'
试图访问索引范围外的字符会引发 IndexError。索引必须是一个整数,不能使用 float 或其他类型,这将引发 TypeError。
# 索引必须在范围内
>>> s[10]
...
IndexError: string index out of range
# 索引必须是整数
>>> s[1.5]
...
TypeError: string indices must be integers
切片操作(slice)是一种很方便的方法,用于引用序列(通常是字符串和列表)的子部分。
切片操作的语法格式:
[start:stop:step]
通过上图,其实也可以很直观地看到切片。
>>> s = 'Hello'
>>>
>>> s[1:4] # 第 2 个到第 4 个字符
'ell'
>>>
>>> s[1:] # 第 2 个到最后一个字符(将索引默认设置为字符串的开始或结束)
'ello'
>>>
>>> s[1:100] # 索引太大,被截断至字符串长度处
'ello'
>>>
>>> s[:] # 所有字符(从开始到结束)
'Hello'
PS: s[:] 形式会忽略开始和结束索引,总是获得一个完整的副本。是 pythonic 使用的方式,用于复制序列(例如:字符串或列表)。
和提取字符类似,切片操作也可以使用反向索引:
>>> s[-4:-1] # 第 2 个到第 4 个字符
'ell'
>>>
>>> s[:-3] # 开始到第 2 个字符
'He'
>>>
>>> s[-3:] # 第 3 个到最后一个字符
'llo'
对于任何索引 n,s[:n] + s[n:] == s
是一个整齐的切片,甚至对于负数或超出界限的值也是如此。换一种说法,s[:n]
和 s[n:]
总是将字符串分成两部分,来保存所有的字符。
字符串是不可变的,也就是说,一旦分配了字符串的元素就不能被更改。
但是,可以将不同的字符串重新分配给同一个变量。
>>> s = 'Hello'
>>> s[2] = 'a'
...
TypeError: 'str' object does not support item assignment
>>>
>>> s = 'Python'
>>> s
'Python'
无法从字符串中删除字符,但是可以使用关键字 del
完全删除字符串。
>>> del s[2]
...
TypeError: 'str' object doesn't support item deletion
>>>
>>> del s
>>> s
...
NameError: name 's' is not defined
字符串能成为 Python 中最常用的数据类型之一,很大原因是因为它使用非常方便,提供了大量的字符串操作,例如:连接字符串、遍历字符串…
所有的序列(例如:字符串、列表)都可以进行以下基本操作:
+
:连接两个序列*
:重复序列元素in
:判断元素是否在序列中min()
:返回最小值max()
:返回最大值len()
:返回序列长度enumerate()
:返回一个枚举对象,包含字符串中所有元素的索引和值(作为一对)连接是指将多个字符串合并为一个单独的字符串。
>>> s1 = "Hello,"
>>> s2 = " World!"
>>>
>>> s = s1 + s2 # 连接字符串
>>> s
'Hello, World!'
如果想在不同的行中连接字符串,可以使用括号。
>>> # 两个字符串一起
>>> 'Hello,' ' World!'
'Hello, World!'
>>>
>>> # 使用括号
>>> s = ('Hello,'
... ' World!')
>>> s
'Hello, World!'
操作符 +
不会将数字或其他类型自动转换为字符串形式,需要通过 str() 函数将值转换为字符串形式,以便它们可以与其他字符串组合。
>>> age = 18
>>>
>>> s = 'My age is ' + age
...
TypeError: Can't convert 'int' object to str implicitly
>>>
>>> s = 'My age is ' + str(age)
>>> s
'My age is 18'
操作符 *
用于以指定的次数来重复字符串。有时很好用,比如打印一条华丽的分割线:
>>> s = 'Hello'
>>>
>>> s * 3 # 重复字符串 3 次
'HelloHelloHello'
>>>
>>> print('-' * 20) # 无需输入很多 -
--------------------
在一个字符串中,每个字符在计算机中都有对应的 ASCII 码。min() 和 max() 就是根据对应的 ASCII 码进行比较的,从而获取最小值和最大值对应的字符。
Python 提供了两个内置函数 ord() 和 chr(),用于字符和 ASCII 码之间的转换。
>>> ord('H') # 字符转 ASCII 码
72
>>>
>>> chr(72) # ASCII 码转字符
'H'
别犹豫啦,开始比较吧!
>>> s = 'Hello'
>>>
>>> min(s) # 最小字符
'H'
>>>
>>> max(s) # 最大字符
'o'
使用关键字 in
,可以测试字符串中是否包含指定的子串。
>>> 't' in 'python'
True
>>>
>>> 'th' not in 'python'
False
要获取一个字符串的长度,可以使用内置函数 len():
>>> s = 'Hello'
>>>
>>> len(s) # 字符数
5
使用 for 循环,可以遍历一个字符串。
# 查找字符串中 l 的数量
count = 0
for letter in 'Hello':
if (letter == 'l'):
count += 1
print(count, 'letters found')
还可使用 enumerate(),它会返回一个枚举对象,包含字符串中所有元素的索引和值(作为一对),这对于迭代很有用。
s = 'Hello'
e = list(enumerate(s))
print(e)
for index, item in e:
print(index, item)
运行程序,输出如下:
[(0, ‘H’), (1, ‘e’), (2, ‘l’), (3, ‘l’), (4, ‘o’)]
0 H
1 e
2 l
3 l
4 o
字符串有许多方法,可以通过 dir() 来查看方法列表:
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
这么多,当然不需要逐一介绍了,重在掌握如何使用(授人以鱼不如授人以渔),能做到随用随查就好。
利用 help() 函数,可以查看函数或模块用途的详细说明:
>>> help(str.lower)
Help on method_descriptor:
lower(...)
S.lower() -> str
Return a copy of the string S converted to lowercase.
(END)
注意: 要终止查询,使用 q 键。
按照说明,可以在交互模式下进行实验,这里仅列举一些比较常用的方法。
>>> s = 'Hello'
>>>
>>> s.lower() # 转换所有字符为小写
'hello'
>>>
>>> s.upper() # 转换所有字符为大写
'HELLO'
>>>
>>> s.find('ll') # 返回子串的开始索引
2
>>>
>>> s.endswith('llo') # 检查字符串是否以指定的子串结束
True
>>>
>>> s.isdigit() # 检查字符串是否只包含数字
False
>>>
>>> s.replace('ll', 'r') # 替换字符串中的子串
'Hero'
>>>
>>> s = 'I like Python'
>>>
>>> s.split() # 分割字符串
['I', 'like', 'Python']