吉吉:
python字符串
计算机中表示文本的最基本的单位是字符,包括可打印字符和不可打印的控制字符。
- 可打印字符包括:
英文的大小写字母’a’’z’,’A’’Z’
数字字符’0’~’9’
标点符号和一些键盘上的常见符号 - 不可打印的控制字符:回车、换行等
- Python 3.x完全支持中文字符,默认使用UTF8编码格式,无论是一个数字、英文字母,还是一个汉字,都按一个字符对待和处理。
>>> s = '中国山东烟台'
>>> len(s) #字符串长度函数,或者包含的字符个数
6
>>> s = '中国山东烟台ABCDE' #中文与英文字符同样对待,都算一个字符
>>> len(s)
11
>>> 姓名 = '张三'#使用中文作为变量名
>>> print(姓名) #输出变量的值
张三
字符串常量
- 字符串可以使用双引号或单引号封装,但前后必须一致。三单引号(’’’ ’’’)和三双引号 ( “”" “”" )表示可以跨行的字符串。
- 字符串常量表示
>>> "hello" #" hello "和'hello'表示的都是字符串hello。
'hello'
>>> 'hello'
'hello'
单引号、双引号、三单引号、三双引号可以互相嵌套,用来表示复杂字符串
- Python还支持只有引号的空字符串。
>>> ''
''
>>> ""
""
- Python同样支持以“\”为前缀的转义字符,例如使用转义字符“\n”可以在输出时使字符串换行。
>>> print( "hello everyone \n today is a great day!“)
hello everyone
today is a great day!
Python的转义字符
\b:退格,把光标移动到前一列位置
\f:换页符
\n:换行符
\r:回车
\t:水平制表符
\v垂直制表符
>>> print('\101') #三位八进制数对应的字符
A
>>> print('\x41') #两位十六进制数对应的字符
A
>>> print(‘我是\u4e2d\u56fd\u4eba!') #四位十六进制数表示的Unicode字符
我是中国人!
原始字符串
- 字符串界定符前面加字母r表示原始字符串,使得解释器不对串中的特殊字符进行转义,但字符串的最后一个字符不能是\。
- 加字母r表示原始字符串
>>> path = ‘C:\Windows\notepad.exe‘#path指向代表记事本的地#址的字符串
>>> print(path) #字符\n被转义为换行符
C:\Windows
otepad.exe
>>> path = r'C:\Windows\notepad.exe' #原始字符串,任何字符都不转义
>>> print(path)
C:\Windows\notepad.exe
原始字符串主要用于正则表达式、文件路径或者URL的场合。可以少写’/’。(重点)
##字符串类型数据的基本计算
###连接和复制操作
- 联接运算示例
>>> 'shang'+'hai'
'shanghai‘
>>> name='李明'
>>> birth_place='shanghai'
>>> message=name+' is from '+birth_place+'.'
>>> print(message)
'李明 is from shanghai.'
- 复制运算示例
>>> "hi "*5
'hi hi hi hi hi '
>>> s="hi"
>>> t=s*3
>>> print(t)
hihihi
索引操作
- 使用方括号来获取字符串中指定的某个字符,用法是:
<字符串>[<数值表达式>]
字符串索引示例
>>> "Student"[5]
'n'
>>> s="hello python!"
>>> s[0]
'h'
>>> i=10
>>> s[i+1]
'n'
>>> s[-1] #末尾字符可以方便定位到末尾字符
'!'
- 字符串修改错误示例
>>> s[5]='i'
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
s[5]='i'
TypeError: 'str' object does not support item assignment
出错提示给出类型错误:str对象不支持对其成员赋值。即字符串是不可变对象
###字符串切片(获取字符串的子串)
- <字符串>[ start:end]
strat是切片的开始位置,end是切片结束位置,注意返回的切片内容从start开始到end位置之前结束。(注意是之前) - 子串索引示例
>>>s=“hello python!”
>>> s[0:2]
'he'
>>> s[2:4]
'll'
>>>s[:2]# 前面的两个字符
‘he'
>>> s[2:]# 除了开始2个字符的所有字符
'llo python!'
子串测试操作
- 子串测试操作in可以测试一个子串是否存在于一个字符串中,计算返回布尔值,用法为:
<子串> in <字符串> - 子串测试操作示例
>>>s=“hello python!”
>>> 'py' in s
True
>>> t='the'
>>> t in s
False
str对象S的常用方法
- str对象方法示例1
- lower()、upper()、capitalize()、title()
>>> s = "What is Your Name?"
>>> print(s)
What is Your Name?
>>> s.lower() #返回小写字符串
'what is your name?'
>>> s.upper() #返回大写字符串
'WHAT IS YOUR NAME?'
>>> s.capitalize() #字符串首字符大写
'What is your name?'
>>> s.title()#每个单词的首字母大写
'What Is Your Name?'
>>> print(s) #s不变
What is Your Name?
存储数据时,方法lower()很有用。很多时候,你无法依靠用户来提供正确的大小写,因此 需要将字符串先转换为小写,再存储它们。以后需要显示这些信息时,再将其转换为最合适的大小写方式。(重点)
----------str对象方法示例2
- strip()、lstrip()、rstrip()
>>> s=' hello python '
>>> t1,t2,t3=s.strip(),s.lstrip(),s.rstrip()
>>> s
' hello python '
>>> print(t1,t2,t3,sep="#")
hello python#hello python # hello python
>>> s
' hello python '
调用strip函数去除字符串的前后空格,它的作用是返回一个去除了原字符串的前后空格的新串。(注意是新字符串)
- str对象方法示例3
- find()、count()
s='hello python'
>>> s.find('he') #求子串'he'第一次出现的位置
0
>>> s.count('h') #求'h'出现的次数
2
- str对象方法示例4
- replace()
>>> s="中国,中国"
>>> s
中国,中国
>>>s1=s.replace("中国", "中华人民共和国")
>>> s1
‘中华人民共和国,中华人民共和国’
后者代替前者
- 测试用户输入中是否有敏感词,如果有的话就把敏感词替换为3个星号***。
>>> words = ('测试', '非法', '暴力', '话')
>>> text = '这句话里含有非法内容'
>>> for word in words:
if word in text:
text = text.replace(word, '***')
>>> text
'这句***里含有***内容'
str对象方法示例5
split()
- split()和方法用来以指定字符为分隔符,将字符串左端和右端开始将其分割成多个字符串,并返回包含分割结果的列表。
>>> s="apple,peach,banana,pear"
>>> li=s.split(",")
>>> li
["apple", "peach", "banana", "pear"]
- 如果不指定分隔符,则字符串中的任何空白符号(包括空格、换行符、制表符等等)都将被认为是分隔符,把连续多个空白字符看作一个,返回包含最终分割结果的列表。(注意分割结果为列表)
>>> s = 'hello world \n\n My name is Dong '
>>> s.split()
['hello', 'world', 'My', 'name', 'is', 'Dong']
>>> s = '\n\nhello\t\t world \n\n\n My name\t is Dong '
>>> s.split()
['hello', 'world', 'My', 'name', 'is', 'Dong']
str对象方法示例6
- join()
字符串连接
>>> li=["apple", "peach", "banana", "pear"]
>>> sep=","
>>> s=sep.join(li)
>>> s
"apple,peach,banana,pear"
str对象可用的内置函数
- 除了字符串对象提供的方法以外,很多Python内置函数也可以对字符串进行操作,例如:
>>> x = 'Hello world.'
>>> len(x)#字符串长度
12
>>> max(x)#最大字符
'w'
>>> min(x)
' '
以董富国编著的《python程序设计》为主要参考