Python字符串

Python是一门功能强大且广泛应用的编程语言,而对于许多开发者来说,字符串处理是Python编程中的一个核心部分。

一、引号标示字符串

Python可以操作文本,也就是字符串(str类型)。字符串可以包含各种字符,例如标点符号、单词、名称和句子等。在Python中,字符串可以使用成对的单引号或双引号来标示,两者的结果完全相同。

>>>'spam eggs' # single quotes
'spam eggs'
>>>"Paris rabbit got your back :)! Yay!" # double quotes
'Paris rabbit got your back :)! Yay!'
>>>'1975' # digits and numerals enclosed in quotes are also strings
'1975'

为了标示引号本身,我们需要用反斜杠进行转义,即在前面加一个 \,或使用另一种引号类型:

>>>'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>>"doesn't" # ...or use double quotes instead
"doesn't"
>>>'"Yes," they said.'
'"Yes," they said.'
>>>"\"Yes,\" they said."
'"Yes," they said.'
>>>'"Isn\'t," they said.'
'"Isn\'t," they said.'

在Python shell中,字符串的定义和输出可能会有所不同。使用 print() 函数时,引号会被省略,并且特殊字符会被解释为换行符等特殊用途,产生更易读的输出:

>>>s = 'First line.\nSecond line.' # \n means newline
>>>s # without print(), special characters are included in the string
'First line.\nSecond line.'
>>>print(s) # with print(), special characters are interpreted, so \n produces new line
First line.
Second line.

如果不想让前置 \的字符转义成特殊字符,可以使用原始字符串,在引号前加上 r :

>>>print('C:\some\name') # here \n means newline!
C:\some
ame
>>>print(r'C:\some\name') # note the r before the quote
C:\some\name

原始字符串有一个微妙的限制:一个原始字符串不能以奇数个 \ 字符结束

字符串字面值可以包含多行内容。一种实现方式是使用三重引号: """...""" 或 '''...''' 。在字符串中会自动包含行结束符,但也可以在换行处使用`\`来避免这种情况。例如:

print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")

输出如下(注意开始的换行符没有被包括在内):

Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to

二、合并和重复

字符串可以用加号 + 合并(连接在一起),也可以用乘号 * 重复。例如:

>>># 3 times 'un', followed by 'ium'
>>>3 * 'un' + 'ium'
'unununium'

相邻的两个或多个字符串字面值会自动合并:

>>>'Py' 'thon'
'Python'

这个特性在拼接过长的字符串时非常有用:

>>>text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>>text
'Put several strings within parentheses to have them joined together.'

这个功能只能用于两个字面值,不能用于变量或表达式:

>>>prefix = 'Py'
>>>prefix 'thon' # can't concatenate a variable and a string literal
File "<stdin>", line 1
prefix 'thon'
^^^^^^
SyntaxError: invalid syntax
>>>('un' * 3) 'ium'
File "<stdin>", line 1
('un' * 3) 'ium'
^^^^^
SyntaxError: invalid syntax

要合并多个变量,或者将变量与字符串字面值合并,需要使用加号 +。

>>>prefix + 'thon'
'Python'

三、索引和切片操作

字符串支持索引(下标访问),第一个字符的索引是0。单个字符没有专门的类型,就是长度为一的字符串,例如:

>>>word = 'Python'
>>>word[0] # character in position 0
'P'
>>>word[5] # character in position 5
'n'

索引还支持负数,用负数索引时表示从右边开始计数:

>>>word[-1] # last character
'n'
>>>word[-2] # second-last character
'o'
>>>word[-6]
'P'

注意:-0 和 0 是一样的,因此负数索引从 -1 开始。

除了索引之外,字符串还支持切片操作。索引用于获取单个字符,而切片允许获取子字符串。

>>>word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>>word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'

切片索引有默认值。省略开始索引时,默认为0;省略结束索引时,默认为字符串的结尾。例如:

>>>word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>>word[4:] # characters from position 4 (included) to the end
'on'
>>>word[-2:] # characters from the second-last (included) to the end
'on'

注意:切片的输出结果包括起始位置,但不包括结束位置。因此,s[:i] + s[i:]总是等于原始字符串 s:

>>>word[:2] + word[2:]
'Python'
>>>word[:4] + word[4:]
'Python'

也可以这样理解切片,索引指向的是字符之间的位置。第一个字符的左侧标记为0,最后一个字符的右侧标记为n,n 是字符串长度。例如:

+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1

第一行数字表示字符串中索引 0...6 的位置,第二行数字表示对应的负数索引位置。切片 [i:j] 由 i 和 j 之间所有对应的字符组成。对于使用非负索引的切片,如果两个索引都未越界,则切片的长度是结束索引减去开始索引。例如,word[1:3] 的长度是2。

如果索引越界则会引发错误:

>>>word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

但是,切片操作会自动处理越界索引。例如:

>>>word[4:42]
'on'
word[42:]
''

Python中的字符串是不可改变的(immutable)。因此,给字符串的某个索引位置赋值会报错:

>>>word[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>word[2:] = 'py'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

要生成一个不同的字符串,需要创建一个新的字符串:

>>>'J' + word[1:]
'Jython'
>>>word[:2] + 'py'
'Pypy'

内置函数 len() 可以返回字符串的长度:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
广告合作
QQ群号:707632017

温馨提示:

1、本网站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。邮箱:2942802716#qq.com。(#改为@)

2、本站原创内容未经允许不得转裁,转载请注明出处“站长百科”和原文地址。

目录