1.创建字符串。
创建字符串就跟创建变量一样很简单。使用引号将字符串内容包含起来就好,可以用单引号,双引号,三引号。
>>> S = 'abc'
>>> S
'abc'
>>> S = "abc"
>>> S
'abc'
>>> S = """abc"""
>>> S
'abc'
使用单引号的时候,内容可以包含双引号,反之使用双引号时,内容一刻包含单引号,也就是说引号可以交替使用。
>>> S = 'abc"d'
>>> S
'abc"d'
>>> S = "abc'd"
>>> S
"abc'd"
>>> S = 'abc'd'
SyntaxError: invalid syntax
>>> S = "abc"d"
SyntaxError: invalid syntax
使用三引号时,单引号自动转义输出,三引号可以换行操作。
>>> S = """
a
b
c
"""
>>> S
'\na\nb\nc\n' #直接输出时,转义字符 不实现。
>>> print(S)
a
b
c
>>> S = """abc'd abc"abc"""
>>> S
'abc\'d abc"abc'<span style="white-space:pre"> #直接输出时,单引号以转义字符的形式输出
>>> print(S)
abc'd abc"abc
2.使用字符串。
跟其他序列一样,字符串使用切片索引就好了。但是字符串不能修改。
>>> S = 'abc'
>>> S[0]
'a'
>>> S[0] = 'b' #试图修改报错。
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
S[0] = 'b'
TypeError: 'str' object does not support item assignment
切片。
>>> S = 'abcdef'
>>> S
'abcdef'
>>> S[1:3]
'bc'
>>> S[5:1:-2]
'fd'
>>> S[1:3:2]
'b'
其他都跟列表,元组类似,在此不更多叙述。
3.用 ‘ + ’ 更改字符串。
字符串不能够修改,但是非要改变其中的内容也是可以实现的,就是使用‘ + ’ 来更改字符串。
>>> S = 'abcdef'
>>> S
'abcdef'
>>> S = S[1:] + 'python' #用 1 后面的内容加上新的内容,包含 1 。
>>> S
'bcdefpython'
>>> S = 'abcdef'
>>> S
'abcdef'
>>> S = S[:2] + 'python' #用 2 之前的内容加上新的内容 ,不包含 2 。
>>> S
>>>'abpython'
>>> S = 'abcdef'
>>> S
'abcdef'
>>> S = S[:] + 'python' #没有参数的话直接在最后加上新内容
>>> S
'abcdefpython'
如果有步进值的话,就是保留相应的元素,然后再加上新的内容。
>>> S = 'abcdef'
>>> S
'abcdef'
>>> S = S[1:3:2] + 'python'
>>> S
'bpython'
>>> S = 'abcdef'
>>> S
'abcdef'
>>> S = S[1:4:2] + 'python'
>>> S
'bdpython'
4.删除字符串。
由于字符串是不能变得,所以不可能只删除一个元素,只能是清除一个字符串的内容,然后重新赋值。或者是把不需要的元素剔除后再重新组成一个字符串。
给字符串赋空值来清空。此时字符串的存在,输出为空。
>>> S = 'abc'
>>> S
'abc'
>>> S = ''
>>> S
''
>>> S = 'bcd'
>>> S
'bcd'
>>> S = 'abc'
>>> S
'abc'
>>> del S
>>> S
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
S
NameError: name 'S' is not defined
>>> S = 'abc'
>>> S
'abc'
>>> S[0]
'a'
>>> del S[0]
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
del S[0]
TypeError: 'str' object doesn't support item deletion
如果只想剔除其中的一个元素,那么需要先剔除后再重新组成一个字符串。
例如:如果想剔除Hello World 中的W 可以这样做。
>>> S = 'Hello World'
>>> S
'Hello World'
>>> S = S[:6] + S[7:]
>>> S
'Hello orld'
5.字符串 ‘ + ’ ‘ *’操作。
Easy。
>>> S = S[:6] + S[7:]
>>> S
'Hello orld'
>>> S = 'Hello World'
>>> S
'Hello World'
>>> S + S
'Hello WorldHello World'
>>> S*3
'Hello WorldHello WorldHello World'
>>> S = 'Hello World'
>>> S
'Hello World'
>>> S + S
'Hello WorldHello World'
>>> S <span style="white-space:pre"> #原本S没有改变
'Hello World'
>>> S = S + S <span style="white-space:pre"> #原本S改变了
>>> S
'Hello WorldHello World'
6.成员操作符。
在序列中可以使用成员操作符,字符串也是如此。
in , not in。顾名思义,用来判断是否存在某个元素,返回布尔值,True或者False。
>>> S = 'abc'
>>> S
'abc'
>>> 'a' in S
True
>>> 'A' in S
False
>>> 'A' not in S
True
>>> 'ab' in S
True
>>> 'ac' in S
False