python第一章-字符串

来源:互联网 发布:微云for mac 编辑:程序博客网 时间:2024/06/05 15:10

python第一章-字符串

除了数字,python 还可以操作字符串,字符串可以用多种方式被展现。它们可以存在于单引号或者双引号中:

>>> ’spam eggs’
’spam eggs’
>>> ’doesn\’t’
"doesn’t"
>>> "doesn’t"
"doesn’t"
>>> ’"Yes," he said.’
’"Yes," he said.’
>>> "\"Yes,\" he said."
’"Yes," he said.’
>>> ’"Isn\’t," she said.’
’"Isn\’t," she said.’


解释器输出字符串操作结果,如同和它们输入的方式一样。在引号里面的引号需要通过反斜杠进行转义来显示正确的数值。如果字符串中包含单引号而没有双引号,则字符串应该被双引号包围。否则用单引号包围。Print()方法可以对输入的字符输出更可读的结果。字符创常量可以用不同的方法分在好多行。可以用反斜杠作为行最后一个字符,用来实现与下一行的逻辑连接。例如:

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
print(hello)
注意新行仍然需要被嵌入在字符串中,并且新行尾部需要一个反斜杠。例如打印结果如下:
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.


或则,可用一对三个引号或者“‘把字符串包围, 当运行三个字符串的时候,行尾不是没有转义,而是包含着字符中了。因此,如下利用一个反斜杠来避免无用的初始化空行。

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


如果我们想吧字符串当做输入字符,\n 字符不被转为新行,而是作为代码中的结束符。都当做数据包含在字符串中。例如:

hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)
打印结果:
This is a rather long string containing\n\
several lines of text much as you would do in C.


字符串还可以用+ 操作符进行相加和* 操作符进行重复。例如:

>>> word = ’Help’ + ’A’
>>> word
’HelpA’
>>> ’<’ + word*5 + ’>’
’<HelpAHelpAHelpAHelpAHelpA>’
两个彼此相邻的字符串可以自动相连接。上面第一行可以被写成”Help”A”: 这种方法主要用作两
个字符串变量,而不是任意字符串表达式。
>>> ’str’ ’ing’ # <- This is ok
’string’
>>> ’str’.strip() + ’ing’ # <- This is ok
’string’
>>> ’str’.strip() ’ing’ # <- This is invalid
File "<stdin>", line 1, in ?
’str’.strip() ’ing’
^
SyntaxError: invalid syntax


像C 一样,字符串可以被索引。字符串的第一个字符的下标是0,这不需要任何的分割符。一个字符就简单说就是长度为1 的字符串。犹如在图表编程语言中,子字符串可以被切片符号表示。两个字符被冒号分割。例如:

>>> word[4]
’A’
>>> word[0:2]
’He’
>>> word[2:4]
’lp’
切片索引有自己的默认值,前面确实表示默认为0,后面确实表示默认为字符串的长度。
>>> word[:2] # The first two characters
’He’
>>> word[2:] # Everything except the first two characters
’lpA’

不像C 语言的字符串,python 字符串不可以改变,如果在字符串中给特定的索引设值会导致错误:
>>> word[0] = ’x’
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: ’str’ object does not support item assignment
>>> word[:1] = ’Splat’
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: ’str’ object does not support slice assignment
但是通过结合字符串内容可以创建一个新的字符串是容易而有效的。
>>> ’x’ + word[1:]
’xelpA’
>>> ’Splat’ + word[4]
’SplatA’
一个有用的不变切分表达式就等于字符串。
>>> word[:2] + word[2:]
’HelpA’
>>> word[:3] + word[3:]
’HelpA’

不正确的切片索引可以被智能的处理。如果索引大于字符串长度,则用字符串长度代替。如果上索引值小于下索引则会返回一个空字符串。
>>> word[1:100]
’elpA’
>>> word[10:]
’’
>>> word[2:1]
’’
索引值可以为负数,表示从右边开始计数。例如
>>> word[-1] # The last character
’A’
>>> word[-2] # The last-but-one character
’p’
>>> word[-2:] # The last two characters
’pA’
>>> word[:-2] # Everything except the last two characters
’Hel’
但是要注意: -0 和0 的作用是相同的。因此不会从右边开始计数。
>>> word[-0] # (since -0 equals 0)
’H’
超出负数的索引会被截断,但不要尝试用超出负数的索引做单个元素的索引:
>>> word[-100:]
’HelpA’
>>> word[-10] # error
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range

记住切片如何工作的一种方法就是把索引认为是两个字符之间的节点。这个字符串的左边下限为0, 右边上限为n.
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1

对于没有负数的索引,切片的长度与索引的长度不相同。如果两个都有界限,例如,长度就等于两者之差。
word[1:3] 的长度就是2.内置函数的方法len()就会返回字符串的长度:
>>> s = ’supercalifragilisticexpialidocious’
>>> len(s)
34
关于编码:
从3.0 开始python 支持所有的编码格式。

如果你想在字符串中包含特殊的字符,你可以利用python Unicode-escape 编码进行实现。下面例子就是很好展示:
>>> ’Hello\u0020World !’
’Hello World !’
转义字符串\u0020 表示在给定的位置插入空格(空格的编码就是0x0020)除了这些标准的字符编码以外,python 还提供了一整套其他形式的编码来在已知的编码基础上创建特定编码字符串。

为了把一个字符串转化为特殊编码的字符,字符串对象提供了一种方法encode()方法。编码的小写字母是引用参数:
>>> "Äpfel".encode(’utf-8’)
b’\xc3\x84pfel’



0 0