Python 字符串 string slicing

来源:互联网 发布:射手播放器 mac破解版 编辑:程序博客网 时间:2024/05/29 21:18

1、字符串放在 '' 和 "" 是一样的结果,右斜杠 \ 用于转译 单斜杠或者双斜杠;
当 单引号 '' 里面需要显示单引号时,可以使用右斜杠 \ 转译,双引号也是如此;但是双引号中的单引号 和 单引号中的双引号 不用右斜杠 \ 转译
>>> '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," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

2、使用 print() 函数,会消除所有封闭的引号,而且打印出转译和特殊字符;\n 产生一个新行;
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she 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.

3、如果不想右斜杠 \ 被作为特殊字符,可以通过在第一个引号前加上 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

4、字符串常量可以使用 三引号:"""...""" 或者 '''...''' 来实现输入多行。行尾会自动包含在字符串中,不过可以通过在末尾放置 \ 来解决

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

如果不加 斜杠 \ :
>>> print("""
... Usage: thingy [OPTIONS]
...      -h
...      -H hostname
... """)

Usage: thingy [OPTIONS]
     -h
     -H hostname

按 Enter 后多了一个空行

5、字符串可以通过 + 和 * 号来实现拼接
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'

两个挨着的字符串常量也会自动拼接(只适合 字符串常量,不适合变量)
>>> 'Py''thon'
'Python'

如果需要拼接 变量和常量,可以使用 +

6、字符串可以被索引,第一个字符的索引为 0。Python 没有字符类型,一个字符就是大小为 1 的字符串
>>> 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 开始

7、除了索引,Python 还支持切片(slicing),获得子串
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

注意到,slicing 表示左闭右开的区间,所以 s[:i]+s[i:] = s
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

缺失的第一个索引默认为 0,缺失的第二个索引默认为 字符串长度大小


8、记住 slices 如何工作的一个方法是,将 索引值 当作指向字符中间的指针。例如:

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

9、使用的索引超过了字符串数值范围,会报错:
>>> word[42]  # the word only has 7 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

但是超过范围的 切片(slicing) 可以正确得处理
>>> word[4:42]
'on'
>>> word[42:]
''

10、Python 中的字符串值是不可变的,常识改变值会报错
>>> word[0] = 'J'
  ...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
  ...
TypeError: 'str' object does not support item assignment

如果你需要不同的字符串,你可以新建一个
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

11、内置函数 len() 返回字符串的长度
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

0 0
原创粉丝点击