python数据类型--字符串


3.1.2。字符串

除数字外,Python还可以操纵字符串,该字符串可以用几种方式表示。它们可以用单引号('...')或双引号("...")括起来,结果相同2。 \可用于转义引号:

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> '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.'

在交互式解释器中,输出字符串用引号引起来,特殊字符用反斜杠转义。尽管有时这看起来可能与输入有所不同(括起来的引号可能会改变),但这两个字符串是等效的。如果字符串包含单引号而不包含双引号,则将字符串括在双引号中;否则,将其括在单引号中。该print()函数通过省略括号引号并输出转义的和特殊字符来产生更具可读性的输出:


>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a 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

字符串文字可以跨越多行。一种方法是使用三引号: """..."""'''...'''。行尾会自动包含在字符串中,但是可以通过\在行尾添加a来防止这种情况。下面的例子:

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'

请注意如何始终包括开始,而总是排除结束。这样可以确保始终等于:s[:i] + s[i:]s


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

切片索引具有有用的默认值。省略的第一索引默认为零,省略的第二索引默认为要切片的字符串的大小。


>>> 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'

记住切片如何工作的一种方法是将索引视为指向字符之间的指针 ,第一个字符的左边缘编号为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字符串无法更改-它们是不可变的。因此,分配给字符串中的索引位置会导致错误:


>>> 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

作者介绍

Image Description

zfajax舫

小时候的梦想是当宇航员,长大的梦想是在北京买套90㎡房的小站长、自媒体人,2014年毕业,后从事过网站开发搭建工作;2016年,创建了张舫博客;20015-至今在北京工作(微信:a7983310)

评论列表

还没有人评论,抢占前排沙发

发表评论

关于作者

Image Description

zfajax舫

小时候的梦想是当宇航员,长大的梦想是在北京买套90㎡房的小站长、自媒体人,2014年毕业,后从事过网站开发搭建工作;2016年,创建了张舫博客;20015-至今在北京工作(微信:a7983310)

关注作者

相关最新发布

Social Links

定制项目外包

Unit 25 Suite 3, 925 Prospect PI,
Beach Resort, 23001

手机号码

18600004319