目录
5.4、额外:findall():找到字符串中的所有子字符串的位置
5.7、capwords()和title():每个单词首字母进行大写操作
5.9、strip() rstrip() lstrip():移除空白字符
1、字符串种类
- 1、unicode-------》type类型在python3中显示的是str类型
- 2、bytes
程序:
>>> "abc"
'abc'
>>> type("abc")
<class 'str'>
>>> "abc".encode("gbk")
b'abc'
>>> type("abc".encode("gbk"))
<class 'bytes'>
>>>
>>> type("中国")
<class 'str'>
>>> type("中国".encode("utf-8"))
<class 'bytes'>
>>> type("中国".encode("utf-8").decode("utf-8"))
<class 'str'>
>>> print("中国".encode("gbk"))
b'\xd6\xd0\xb9\xfa'
>>>
提问1:为什么字符串有2种数据类型,为什么存在bytes类型的数据
答案:只要不是在内存中使用,都是使用的bytes类型,在写文件时,也是使用的bytes类型。网络传输也是使用bytes类型。
在计算机的内存中,统一使用unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为bytes编码用记事本编辑的时候,从文件读取的utf-8字符被转换为unicode字符到内存里面,编辑完成后,保存的时候再把unicode转换成utf-8保存到文件中
提问2:bytes类型怎么使用?
示例:
>>> s=b"abc"
>>> type(s)
<class 'bytes'>
>>> ss=b"光荣之路"
File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> ss="光荣之路".encode("utf-8")
>>> s
b'abc'
>>> ss
b'\xe5\x85\x89\xe8\x8d\xa3\xe4\xb9\x8b\xe8\xb7\xaf'
>>>
>>> ss.decode("utf-8")
'光荣之路'
>>>
>>> s="光荣之路".encode("utf-8").decode("utf-8").encode("gbk")
>>> s
b'\xb9\xe2\xc8\xd9\xd6\xae\xc2\xb7'
>>>
解释说明:
1)当字符串为字母时,可以直接加一个b就可以转换成bytes类型
2)当字符串为中文时,转换为bytes类型,需要使用encode才可以转换,直接写b的形式会报错。
提问3:怎么判断该变量是否为字符串
答案:使用isinstance函数,一般应用在函数传参数时判断传参的类型。
示例:
>>> def add(a,b):
... if (not isinstance (a,str)) or (not isinstance(b,str)):
... return None
... else:
... return a+b
...
>>> add("hello",1)
>>> print(add("hello",1))
None
>>> print(add("a","b"))
ab
>>>
2、字符串转义字符
示例:
1)\(续行符)
>>> print("i am a good boy \
... i hava a ball")
i am a good boy i hava a ball
>>>
2)\\:输出\
>>> print("i am a good boy,\\tomoto" )
i am a good boy,\tomoto
>>>
>>> path="e:\\test\\a.txt"
>>> print(path)
e:\test\a.txt
>>> path=r"e:\test\a.txt"
>>> print(path)
e:\test\a.txt
>>>
3)\n:换行符
>>> print("i am a \n boy")
i am a
boy
>>>
>>> a="a\nb"
>>> print(a)
a
b
>>> a="a\\nb"
>>> print(a)
a\nb
>>>
4)\r :回车
>>> import os
>>> os.linesep
'\r\n'
>>>
- Windows默认的回车是:\r\n
- Linux默认的回车是:\n
- Mac默认的回车是:\n
5)使用单引号、双引号的方法
- 外部用单引号,内部用双引号
- 外部 用双引号,内部用单引号
- 或者内外部相同,用转义符号
示例:
>>> s="i am' ade"
>>> s
"i am' ade"
>>> s='i " dei'
>>> s
'i " dei'
>>> a='i am \' a boy'
>>> a
"i am ' a boy"
>>>
3、字符串运算符
运算符 |
描述 |
+ |
字符串进行拼接 |
* |
字符串重复操作 |
[] |
通过字符串的索引进行查询数据 |
[:] |
截取字符串中的一部分数据 |
r |
|
% |
格式化字符串 |
in / not in |
成员字符串,如果原字符串中包含该字符,返回true,否则,返回false |
示例:
>>> a="hello"
>>> b="world"
>>> a+b
'helloworld'
>>> a*2
'hellohello'
>>> a[-1]
'o'
>>> a[0]
'h'
>>> a[2:6]
'llo'
>>> a[-3:-1]
'll'
>>> "mingtian" in a
False
>>> "a" in a
False
>>> "hel" in a
True
>>>
>>> s="abcdef"
>>> s[1:4]
'bcd'
>>> s[-3:-6:-1]
'dcb'
#如何取出“fdb呢”,有以下几种方案
>>> s[-1:-6:-2]
'fdb'
>>>
>>> s[-1:0:-2]
'fdb'
>>>
>>> s[::-2]
'fdb'
>>>
注意事项:
- 字符串是不可改变的类型,通过id地址可以看出来
当2个不同的变量,都指向一个字符串的内存地址时,两个变量的id值是一样的。
4、字符串格式化
示例: