文章目录
-
- String(字符串)
-
- 一、 Unicode 字符串
- 二、 创建字符串
- 三、 字符串表示
- 四、 字符串操作
- 五、 转义字符
- 六、 字符串运算符
- 七、 字符串格式化
-
- 1、 字符串格式化符号
- 2、 格式化操作符辅助指令
- 3、 字面量格式化字符串
- 八、 字符串内建函数
-
- capitalize()
- center(width, fillchar)
- ljust(width[, fillchar])
- rjust(width,[, fillchar])
- zfill (width)
- count(str, beg= 0,end=len(string))
- bytes.decode(encoding=”utf-8″, errors=”strict”)
- encode(encoding=’UTF-8′,errors=’strict’)
- endswith(suffix, beg=0, end=len(string))
- startswith(substr, beg=0,end=len(string))
- expandtabs(tabsize=8)
- find(str, beg=0, end=len(string))
- rfind(str, beg=0,end=len(string))
- index(str, beg=0, end=len(string))
- rindex( str, beg=0, end=len(string))
- isalnum()
- isalpha()
- isdigit()
- isnumeric()
- islower()
- isupper()
- isspace()
- title()
- istitle()
- join(seq)
- len(s)
- lower()
- upper()
- swapcase()
- lstrip()
- rstrip()
- strip([chars])
- maketrans()
- translate(table, deletechars=””)
- max(str)
- min(str)
- replace(old, new [, max])
- split(str=””, num=string.count(str))
- splitlines([keepends])
- isdecimal()
String(字符串)
string、list 和 tuple 都属于 sequence(序列)
一、 Unicode 字符串
Python3中,所有的字符串都是Unicode字符串(Python2中,普通字符串是以8位ASCII码进行存储)
Unicode字符串存储16位unicode字符串,使用时在字符串前面加上前缀 u即可
二、 创建字符串
使用 单引号 ’ 或 双引号 “ 来创建字符串,为变量分配一个值
tips : 单字符在 Python 中作为字符串使用
s1 = '字符串1' #单引号创建
s2 = "字符串2" #双引号创建
s2 = "s" #单字符在py中作为字符串使用
- 1
- 2
- 3
三、 字符串表示
-
没有单独的字符类型,一个字符就是长度为 1 的字符串(不区分单字符与多字符)
-
单引号 ’ 或双引号 “ 括起来表示字符串(单引号和双引号使用完全相同)
-
使用三引号(’’’ 或 “””)可以指定一个多行字符串,反斜杠\也可以作为续行符
-
字符串不能改变,比如向一个索引位置赋值,word[0] = ‘m’ 会导致错误
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
- 1
- 2
- 3
- 4
四、 字符串操作
字符串截取:
变量[头下标:尾下标]
变量[头下标:尾下标:步长]两种索引方式:
从左往右,以0开始
从右往左,以-1开始
字符串连接:+
字符串复制:* n(n代表复制的次数)
级联字符串:如”this ” “is ” “string”会被自动转换为this is string
代码示例:
str = '123456789'
print(str) # 输出字符串
print(str[:]) # 输出所有字符
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[-6:-2]) #输出字符串倒数第六个到倒数第三个的所有字符[-6,-2)
print(str[2:5]) # 输出从第三个开始到第五个的字符[2,5)
print(str[2:]) # 输出从第三个开始后的所有字符
print(str[1:5:2]) # 输出从第二个开始到第五个且每隔一个的字符(步长为2)
print(str * 2) # 输出字符串两次
print(str + '你好') # 连接字符串
'''
输出结果:
123456789
123456789
12345678
1
4567
345
3456789
24
123456789123456789
123456789你好
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
五、 转义字符
反斜杠 \ 转义特殊字符
转义字符 | 描述 |
---|---|
\(在行尾时) | 续行符 |
\\ | 反斜杠符号 |
\’ | 单引号 |
\” | 双引号 |
\a | 响铃(执行后电脑有响声) |
\b | 退格(Backspace) |
\000 | 空 |
\n | 换行 |
\v | 纵向制表符 |
\t | 横向制表符 |
\r | 回车,将 \r 后面的内容移到字符串开头,并逐一替换开头部分的字符,直至将 \r 后面的内容完全替换完成 |
\f | 换页 |
\yyy | 八进制数,y 代表 0~7 的字符,例如:\012 代表换行 |
\xyy | 十六进制数,以 \x 开头,y 代表的字符,例如:\x0a 代表换行 |
\other | 其它的字符以普通格式输出 |
代码示例:
print("换行符\:","line1 \
line2 \
line3")
print("空\\000:","\000")
print("纵向制表符\\v:","Hello \v World!")
print("横向制表符\\t:","Hello \t World!")
print("后面内容替换前面内容\\r:",'google runoob taobao\r123456')
print("换页","Hello \f World!")
print("八进制数:","\110\145\154\154\157\40\127\157\162\154\144\41")
print("十六进制数:","\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21")
'''
输出结果:
换行符\: line1 line2 line3
空\000:
纵向制表符\v: Hello World!
横向制表符\t: Hello World!
123456
换页 Hello World!
八进制数: Hello World!
十六进制数: Hello World!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
使用r或者R可以让反斜杠不发生转义
代码示例:
print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
print('\n') # 输出空行
print(r'\n') # 输出 \n
'''
输出结果:
hello
runoob
hello\nrunoob
\n
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
六、 字符串运算符
操作符 | 描述 |
---|---|
+ | 字符串连接 |
* | 重复输出字符串 |
[] | 通过索引获取字符串中字符 |
[ : ] | 截取字符串中的一部分,左闭右开 |
in | 成员运算符,如果字符串中包含给定的字符返回 True |
not in | 成员运算符,如果字符串中不包含给定的字符返回 True |
r/R | 原始字符串,即所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符(原始字符串除在字符串的第一个引号前加上字母 r 或 R 以外,与普通字符串有着几乎完全相同的语法) |
% | 格式字符串 |
代码示例:
a = "Hello"
b = " World!"
print("a + b :", a + b)
print("a * 2 :", a * 2)
print("a[1] :", a[1])
print("a[1:4] :", a[1:4])
if ("H" in a):
print("\"H\" in a : True(H 在变量 a 中)")
else:
print("\"H\" in a : False(H 不在变量 a 中)")
if ("M" not in a):
print("\"M\" not in a : True(M 不在变量 a 中)")
else:
print("\"M\" not in a : False(M 在变量 a 中)")
print("r'\\n'不发生转义: ",r'\n')
print("R'\\n'不发生转义: ",R'\n')
'''
输出结果:
a + b : Hello World!
a * 2 : HelloHello
a[1] : e
a[1:4] : ell
"H" in a : True(H 在变量 a 中)
"M" not in a : True(M 不在变量 a 中)
r'\n'不发生转义: \n
R'\n'不发生转义: \n
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
七、 字符串格式化
格式字符串:%
字符串输出格式化:将一个值插入到一个有字符串格式符 %s 的字符串中
1、 字符串格式化符号
符号 | 描述 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e | 用科学计数法格式化浮点数 |
%E | 作用同%e,用科学计数法格式化浮点数 |
%g | %f和%e的简写 |
%G | %f 和 %E 的简写 |
%p | 用十六进制数格式化变量的地址 |
代码示例:
print ("这里是 %s ,码龄 %d 年了!" % ('入错行的北北', 1))
'''
输出结果:
这里是 入错行的北北 ,码龄 1 年了!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
2、 格式化操作符辅助指令
符号 | 功能 |
---|---|
* | 定义宽度或者小数点精度 |
– | 左对齐 |
+ | 在正数前面显示加号( + ) |
< sp > | 在正数前面显示空格 |
# | 在八进制数前面显示零(‘0’),在十六进制前面显示’0x’或者’0X’(取决于用的是’x’还是’X’) |
0 | 显示的数字前面填充’0’而不是默认的空格 |
% | ‘%%‘输出一个单一的’%’ |
(var) | 映射变量(字典参数) |
m.n. | m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) |
3、 字面量格式化字符串
python3.6 之后版本添加,新的格式化字符串的语法
在 Python 3.8 的版本中可以使用 = 符号来拼接运算表达式与结果
以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去
代码示例:
name = 'World'
print('Hello %s' % name)
print(f'Hello {name}') # 替换变量
print(f'{1+2}') # 使用表达式
w = {'昵称': '入错行的北北', '码龄': '1年'}
print(f'{w["昵称"]}: {w["码龄"]}')
x = 1
print(f'{x+1}') # python 3.6
print(f'{x+1=}') # Python 3.8
'''
输出结果:
Hello World
Hello World
3
入错行的北北: 1年
2
x+1=2
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
八、 字符串内建函数
方法 | 描述 |
---|---|
capitalize() | 将字符串的第一个字符转换为大写 |
center(width, fillchar) | 返回一个指定宽度 并居中的字符串,fillchar 为填充的字符,默认为空格 |
ljust(width[, fillchar]) | 返回一个原字符串左对齐,fillchar 为填充的字符,默认为空格 |
rjust(width,[, fillchar]) | 返回一个原字符串右对齐,fillchar 为填充的字符,默认为空格 |
zfill (width) | 返回长度为 width 的字符串,原字符串右对齐 |
count(str, beg= 0,end=len(string)) | 用于统计字符串里某个字符出现的次数,可选参数为在字符串搜索的开始与结束位置 |
bytes.decode(encoding=“utf-8”, errors=“strict”) | 以指定的编码格式解码 bytes 对象,默认编码为 ‘utf-8’ |
encode(encoding=‘UTF-8’,errors=‘strict’) | 以指定的编码格式编码字符串,errors参数可以指定不同的错误处理方案 |
endswith(suffix, beg=0, end=len(string)) | 判断字符串是否以指定后缀结尾 |
startswith(substr, beg=0,end=len(string)) | 检查字符串是否是以指定子字符串开头 |
expandtabs(tabsize=8) | 把字符串中的 tab 符号 \t (默认8个空格)转为空格 |
find(str, beg=0, end=len(string)) | 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内 |
rfind(str, beg=0,end=len(string)) | 类似于find()函数,不过从右边开始查找 |
index(str, beg=0, end=len(string)) | 与find()方法大致一样,但是如果str不在字符串中会报异常 |
rindex( str, beg=0, end=len(string)) | 类似于 index(),不过从右边开始 |
isalnum() | 检测字符串是否由字母和数字组成 |
isalpha() | 检测字符串是否只由字母或文字组成 |
isdigit() | 检测字符串是否只由**数字(纯数字)**组成 |
isnumeric() | 检测字符串是否只由数字组成 |
islower() | 检测字符串中的字母是否都是小写字母 |
isupper() | 检测字符串中的字母是否都是大写字母 |
isspace() | 检测字符串是否只由空白字符组成 |
title() | 返回”标题化”的字符串,所有单词都是首字母大写、其余字母为小写 |
istitle() | 检测字符串中所有的单词拼写是否为首字母大写、其余字母为小写 |
join(seq) | 用于将序列中的元素以指定的字符连接生成一个新的字符串 |
len(string) | 返回对象(字符、列表、元组等)长度或项目个数 |
lower() | 字符串中所有大写字符转换为小写 |
upper() | 字符串中的小写字母转换为大写 |
swapcase() | 将字符串中大写转换为小写,小写转换为大写 |
lstrip() | 删除字符串左边的空格或指定字符 |
rstrip() | 删除字符串末尾的空格或指定字符 |
strip([chars]) | 在字符串上执行 lstrip()和 rstrip() |
maketrans() | 创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标 |
translate(table, deletechars=””) | 根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中 |
max(str) | 返回字符串 str 中最大的字母 |
min(str) | 返回字符串 str 中最小的字母 |
replace(old, new [, max]) | 把 将字符串中的 old 替换成 new,替换不超过 max 次 |
split(str=””, num=string.count(str)) | 以 str 为分隔符分割字符串,如果 num 有指定值,则仅分割 num+1 个子字符串 |
splitlines([keepends]) | 按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符 |
isdecimal() | 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false |
capitalize()
将字符串的第一个字符转换为大写,其它字母小写
str.capitalize()
- 参数
无 - 返回值
返回一个首字母大写的字符串
代码示例:
str = "hello WORLD!"
print ("str.capitalize() : ", str.capitalize())
'''
输出结果:
str.capitalize() : Hello world!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
center(width, fillchar)
返回一个指定宽度 并居中的字符串,fillchar 为填充的字符,默认为空格
str.center(width[, fillchar])
- 参数
width :字符串的宽度
fillchar :填充字符(默认为空格) - 返回值
返回一个指定宽度 并居中的字符串
width小于字符串宽度直接返回字符串,否则fillchar填充
代码示例:
str = "[hello]"
print ("str.center(4 ) : ", str.center(4))
print ("str.center(40 ) : ", str.center(40))
print ("str.center(40, '*') : ", str.center(40, '*'))
'''
输出结果:
str.center(4 ) : [hello]
str.center(40 ) : [hello]
str.center(40, '*') : ****************[hello]*****************
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
ljust(width[, fillchar])
返回一个原字符串左对齐,fillchar 为填充的字符,默认为空格
str.ljust(width[, fillchar])
- 参数
width :指定字符串长度
fillchar :填充字符,默认为空格 - 返回值
返回一个指定宽度 并左对齐的字符串
width小于字符串宽度直接返回字符串,否则fillchar填充
代码示例:
str = "[hello]"
print ("str.center(4 ) : ", str.ljust(4))
print ("str.center(40 ) : ", str.ljust(40))
print ("str.center(40, '*') : ", str.ljust(40, '*'))
'''
输出结果:
str.center(4 ) : [hello]
str.center(40 ) : [hello]
str.center(40, '*') : [hello]*********************************
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
rjust(width,[, fillchar])
返回一个原字符串右对齐,fillchar 为填充的字符,默认为空格
str.rjust(width[, fillchar])
- 参数
width :指定字符串长度
fillchar :填充字符,默认为空格 - 返回值
返回一个指定宽度 并右对齐的字符串
width小于字符串宽度直接返回字符串,否则fillchar填充
代码示例:
str = "[hello]"
print ("str.center(4 ) : ", str.rjust(4))
print ("str.center(40 ) : ", str.rjust(40))
print ("str.center(40, '*') : ", str.rjust(40, '*'))
'''
输出结果:
str.center(4 ) : [hello]
str.center(40 ) : [hello]
str.center(40, '*') : *********************************[hello]
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
zfill (width)
返回长度为 width 的字符串,原字符串右对齐
width小于字符串宽度直接返回字符串,否则前面填充0
str.zfill(width)
- 参数
width : 指定字符串的长度。原字符串右对齐,前面填充0 - 返回值
返回一个指定宽度 并右对齐的字符串
width小于字符串宽度直接返回字符串,否则前面填充0
代码示例:
str = "hello world!"
print ("str.zfill : ",str.zfill(2))
print ("str.zfill : ",str.zfill(20))
'''
输出结果:
str.zfill : hello world!
str.zfill : 00000000hello world!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
count(str, beg= 0,end=len(string))
用于统计字符串里某个字符出现的次数,可选参数为在字符串搜索的开始与结束位置
str.count(sub, start= 0,end=len(string))
- 参数
sub : 搜索的子字符串
start : 搜索的起始位置,默认索引值为0
end: 搜索的结束位置,默认为字符串的最后一个位置 - 返回值
返回子字符串在字符串中出现的次数
代码示例:
str="Hello world!"
sub='o'
print ("str.count('o') : ", str.count(sub))
print ("str.count('o', 3, 5) : ", str.count(sub,3,5))
sub='run'
print ("str.count('run') : ", str.count(sub))
'''
输出结果:
str.count('o') : 2
str.count('o', 3, 5) : 1
str.count('run') : 0
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
bytes.decode(encoding=“utf-8”, errors=“strict”)
以指定的编码格式解码 bytes 对象,默认编码为 ‘utf-8’
bytes.decode(encoding=“utf-8”, errors=“strict”)
- 参数
encoding : 使用的编码,如”UTF-8″
errors :设置不同错误的处理方案(默认为 ‘strict’,意为编码错误引起一个UnicodeError,其他可能得值有 ‘ignore’, ‘replace’,‘xmlcharrefreplace’,‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值) - 返回值
返回解码后的字符串
代码示例:
str = "入错行的北北";
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")
print(str)
print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk)
print("UTF-8 解码:", str_utf8.decode('UTF-8', 'strict'))
print("GBK 解码:", str_gbk.decode('GBK', 'strict'))
'''
输出结果:
入错行的北北
UTF-8 编码: b'\xe5\x85\xa5\xe9\x94\x99\xe8\xa1\x8c\xe7\x9a\x84\xe5\x8c\x97\xe5\x8c\x97'
GBK 编码: b'\xc8\xeb\xb4\xed\xd0\xd0\xb5\xc4\xb1\xb1\xb1\xb1'
UTF-8 解码: 入错行的北北
GBK 解码: 入错行的北北
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
encode(encoding=‘UTF-8’,errors=‘strict’)
以指定的编码格式编码字符串,errors参数可以指定不同的错误处理方案
str.encode(encoding=‘UTF-8’,errors=‘strict’)
- 参数
encoding :要使用的编码,如: UTF-8
errors : 设置不同错误的处理方案(默认为 ‘strict’,意为编码错误引起一个UnicodeError,其他可能得值有 ‘ignore’, ‘replace’,‘xmlcharrefreplace’,‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值) - 返回值
返回编码后的字符串,是一个 bytes 对象
代码示例:
str = "入错行的北北";
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")
print(str)
print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk)
print("UTF-8 解码:", str_utf8.decode('UTF-8', 'strict'))
print("GBK 解码:", str_gbk.decode('GBK', 'strict'))
'''
输出结果:
入错行的北北
UTF-8 编码: b'\xe5\x85\xa5\xe9\x94\x99\xe8\xa1\x8c\xe7\x9a\x84\xe5\x8c\x97\xe5\x8c\x97'
GBK 编码: b'\xc8\xeb\xb4\xed\xd0\xd0\xb5\xc4\xb1\xb1\xb1\xb1'
UTF-8 解码: 入错行的北北
GBK 解码: 入错行的北北
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
endswith(suffix, beg=0, end=len(string))
判断字符串是否以指定后缀结尾
str.endswith(suffix[, start[, end]])
- 参数
suffix : 一个字符串或者是一个元素
start :字符串str中的开始位置
end :字符串str中结束位置 - 返回值
如果字符串含有指定的后缀返回 True,否则返回 False
代码示例:
Str='Hello!! world!!'
suffix='!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,5,7))
suffix='beibei'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))
'''
输出结果:
True
True
False
False
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
startswith(substr, beg=0,end=len(string))
检查字符串是否是以指定子字符串开头
str.startswith(substr, beg=0,end=len(string));
- 参数
str : 检测的字符串
substr: 一个字符串或者是一个元素
beg:字符串str中的开始位置
end :字符串str中结束位置 - 返回值
如果检测到字符串则返回True,否则返回False
代码示例:
Str='!!Hello!! world!!'
suffix='!!'
print (Str.startswith(suffix))
print (Str.startswith(suffix,7))
suffix='beibei'
print (Str.startswith(suffix))
print (Str.startswith(suffix, 0, 19))
'''
输出结果:
True
True
False
False
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
expandtabs(tabsize=8)
把字符串中的 tab 符号 \t (默认8个空格)转为空格
在第 0、8、16…等处给出制表符位置,如果当前位置到开始位置或上一个制表符位置的字符数不足 8 的倍数则以空格代替
str.expandtabs(tabsize=8)
- 参数
tabsize : 指定转换字符串中的 tab 符号 \t 转为空格的字符数 - 返回值
返回字符串中的 tab 符号 \t 转为空格后生成的新字符串
代码示例:
str = "Hello\tworld\t!!"
print('原始字符串:', str)
# 默认 8 个空格
print('替换 \\t 符号:', str.expandtabs())
# 2 个空格
print('使用 2 个空格替换 \\t 符号:', str.expandtabs(2))
# 3 个空格
print('使用 3 个空格:', str.expandtabs(3))
# 4 个空格
print('使用 4 个空格:', str.expandtabs(4))
# 5 个空格
print('使用 5 个空格:', str.expandtabs(5))
# 6 个空格
print('使用 6 个空格:', str.expandtabs(6))
'''
输出结果:
原始字符串: Hello world !!
替换 \t 符号: Hello world !!
使用 2 个空格替换 \t 符号: Hello world !!
使用 3 个空格: Hello world !!
使用 4 个空格: Hello world !!
使用 5 个空格: Hello world !!
使用 6 个空格: Hello world !!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
find(str, beg=0, end=len(string))
检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内
str.find(str, beg=0, end=len(string))
- 参数
str : 指定检索的字符串
beg : 开始索引,默认为0
end : 结束索引,默认为字符串的长度 - 返回值
如果包含子字符串返回开始出现的位置,否则返回-1
代码示例:
str1 = "Hello world!!!"
str2 = "world";
print(str1.find(str2))
print(str1.find(str2, 5))
print(str1.find(str2, 10))
'''
输出结果:
6
6
-1
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
rfind(str, beg=0,end=len(string))
类似于find()函数,不过从右边开始查找
str.rfind(str, beg=0 end=len(string))
- 参数
str : 指定检索的字符串
beg : 开始索引,默认为0
end :结束索引,默认为字符串的长度 - 返回值
返回字符串最后一次出现的位置,如果没有匹配项则返回-1
代码示例:
str1 = "~~ hello hello world!"
str2 = "hello"
print (str1.find(str2)) #从左开始找第一个
print (str1.rfind(str2)) #从右开始找第一个
print (str1.find(str2, 0, 10))
print (str1.rfind(str2, 0, 10))
print (str1.find(str2, 10, 0))
print (str1.rfind(str2, 10, 0))
'''
输出结果:
3
9
3
3
-1
-1
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
index(str, beg=0, end=len(string))
与find()方法大致一样,但是如果str不在字符串中会报异常
str.index(str, beg=0, end=len(string))
- 参数
str : 指定检索的字符串
beg : 开始索引,默认为0
end :结束索引,默认为字符串的长度 - 返回值
如果包含子字符串返回开始出现的位置,否则抛出异常
代码示例:
str1 = "Hello world!!!"
str2 = "world";
print(str1.index(str2))
print(str1.index(str2, 5))
print(str1.index(str2, 10))
'''
输出结果:
Traceback (most recent call last):
File "D:\PythonProject\HelloWorld\HelloWorld.py", line 6, in <module>
print(str1.index(str2, 10))
ValueError: substring not found
6
6
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
rindex( str, beg=0, end=len(string))
类似于 index(),不过从右边开始
str.rindex(str, beg=0, end=len(string))
- 参数
str : 指定检索的字符串
beg : 开始索引,默认为0
end :结束索引,默认为字符串的长度 - 返回值
返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常
代码示例:
str1 = "hello hello world!!!"
str2 = "hello";
print(str1.rindex(str2))
print(str1.rindex(str2, 5))
'''
输出结果:
6
6
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
isalnum()
检测字符串是否由字母和数字组成
str.isalnum()
- 参数
无 - 返回值
如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
代码示例:
str = "HelloWorld" # 字符串没有空格
print(str.isalnum())
str = "Hello World"
print(str.isalnum())
'''
输出结果:
True
False
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
isalpha()
检测字符串是否只由字母或文字组成
str.isalpha()
- 参数
无 - 返回值
如果字符串至少有一个字符并且所有字符都是字母或文字则返回 True,否则返回 False
代码示例:
str = "HelloWorld"
print (str.isalpha())
str = "入错行的北北"
print (str.isalpha())
str = "HelloWorld!"
print (str.isalpha())
str = "入错行的北北666"
print (str.isalpha())
'''
输出结果:
True
True
False
False
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
isdigit()
检测字符串是否只由**数字(单纯的数字)**组成
str.isdigit()
- 参数
无 - 返回值
如果字符串只包含数字则返回 True 否则返回 False
代码示例:
str = "123456";
print (str.isdigit())
str = "HelloWorld"
print (str.isdigit())
'''
输出结果:
True
False
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
isnumeric()
检测字符串是否只由数字组成
数字可以是: Unicode 数字,全角数字(双字节),罗马数字,汉字数字
str.isnumeric()
- 参数
无 - 返回值
如果字符串中只包含数字字符,则返回 True,否则返回 False
代码示例:
str = "Hello World2021"
print (str.isnumeric())
str = "20 21"
print (str.isnumeric())
str = "2021"
print (str.isnumeric())
'''
输出结果:
False
False
True
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
islower()
检测字符串中的字母是否都是小写字母
str.islower()
- 参数
无 - 返回值
如果字符串中的字母部分全是小写字母,则返回 True,否则返回 False
代码示例:
str = "Hello World!"
print (str.islower())
str = "hello world!"
print (str.islower())
str = "hello world!嘿嘿!"
print (str.islower())
'''
输出结果:
False
True
True
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
isupper()
检测字符串中的字母是否都是大写字母
str.isupper()
- 参数
无 - 返回值
如果字符串中的字母部分全是大写字母,则返回 True,否则返回 False
代码示例:
str = "HELLO WORLD!"
print (str.isupper())
str = "HELLO WORLD!嘿嘿!"
print (str.isupper())
str = "hello world!"
print (str.isupper())
'''
输出结果:
True
True
False
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
isspace()
检测字符串是否只由空白字符组成
str.isspace()
- 参数
无 - 返回值
如果字符串中只包含空格,则返回 True,否则返回 False
代码示例:
str = " "
print(str.isspace())
str = "Hello World!"
print(str.isspace())
'''
输出结果:
True
False
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
title()
返回”标题化”的字符串,所有单词都是首字母大写、其余字母为小写
非字母后的第一个字母将转换为大写字母
str.title();
- 参数
无 - 返回值
返回”标题化”的字符串,所有单词都是首字母大写、其余字母为小写
非字母后的第一个字母将转换为大写字母
代码示例:
str = "hello world!!"
print (str.title())
str = "bye 4g hello 5g"
print (str.title())
'''
输出结果:
Hello World!!
Bye 4G Hello 5G
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
istitle()
检测字符串中所有的单词拼写是否为首字母大写、其余字母为小写
str.istitle()
- 参数
无 - 返回值
如果字符串中所有的单词拼写首字母为大写、字母为小写则返回 True,否则返回 False
代码示例:
str = "Hello World!"
print(str.istitle())
str = "Hello world!"
print(str.istitle())
'''
输出结果:
True
False
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
join(seq)
用于将序列中的元素以指定的字符连接生成一个新的字符串
str.join(sequence)
- 参数
sequence : 要连接的元素序列 - 返回值
返回通过指定字符连接序列中元素后生成的新字符串
代码示例:
s1 = "-"
s2 = ""
seq = ("h", "e", "l", "l", "o") # 字符串序列
print (s1.join( seq ))
print (s2.join( seq ))
'''
输出结果:
h-e-l-l-o
hello
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
len(s)
返回对象(字符、列表、元组等)长度或项目个数
len( s )
- 参数
s :对象 - 返回值
返回对象长度
代码示例:
l = [1,2,3,4,5]
print(len(l))
s = "Hello World!"
print(len(s))
'''
输出结果:
5
12
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
lower()
字符串中所有大写字符转换为小写
str.lower()
- 参数
无 - 返回值
返回将字符串中所有大写字符转换为小写后生成的字符串
代码示例:
str = "HELLO WORLD!"
print( str.lower() )
'''
输出结果:
hello world!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
upper()
字符串中的小写字母转换为大写
str.upper()
- 参数
无 - 返回值
返回小写字母转为大写字母的字符串
代码示例:
str = "hello world!!!";
print ("str.upper() : ", str.upper())
'''
输出结果:
str.upper() : HELLO WORLD!!!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
swapcase()
将字符串中大写转换为小写,小写转换为大写
str.swapcase();
- 参数
无 - 返回值
返回大小写字母转换后生成的新字符串
代码示例:
str = "Hello World!!"
print (str.swapcase())
'''
输出结果:
hELLO wORLD!!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
lstrip()
删除字符串左边的空格或指定字符
str.lstrip([chars])
- 参数
chars : 指定字符 - 返回值
返回删除字符串左边的空格或指定字符后生成的新字符串
代码示例:
str = " Hello World!!! ";
print(str.lstrip());
str = "88888888Hello World!!!8888888";
print( str.lstrip('8') );
'''
输出结果:
Hello World!!!
Hello World!!!8888888
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
rstrip()
删除字符串末尾的空格或指定字符
str.rstrip([chars])
- 参数
chars : 指定删除的字符(默认为空格) - 返回值
返回删除 string 字符串末尾的指定字符后生成的新字符串
代码示例:
str = " Hello World!!! ";
print(str.rstrip());
str = "88888888Hello World!!!8888888";
print( str.rstrip('8') );
'''
输出结果:
Hello World!!!
88888888Hello World!!!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
strip([chars])
在字符串上执行 lstrip()和 rstrip()
该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
str.strip([chars]);
- 参数
chars : 移除字符串头尾指定的字符序列 - 返回值
返回移除字符串头尾指定的字符序列生成的新字符串
代码示例:
str = " Hello World!!! ";
print(str.strip());
str = "88888888Hello World!!!8888888";
print( str.strip('8') );
str = "12345678Hello World!!!87654321";
print( str.strip('1234567') );
'''
输出结果:
Hello World!!!
Hello World!!!
8Hello World!!!8
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
maketrans()
创建字符映射的转换表
对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标
两个字符串的长度必须相同,为一一对应的关系
tips:注:Python3.4 已经没有 string.maketrans() ,取而代之的是内建函数: bytearray.maketrans()、bytes.maketrans()、str.maketrans() 。
str.maketrans(intab, outtab)
- 参数
intab : 字符串中要替代的字符组成的字符串
outtab :相应的映射字符的字符串 - 返回值
返回字符串转换后生成的新字符串
代码示例:
intab = "elord"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "Hello World!!!"
print (str.translate(trantab))
'''
输出结果:
H1223 W3425!!!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
translate(table, deletechars=””)
根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中
str.translate(table)
bytes.translate(table[, delete])
bytearray.translate(table[, delete])
- 参数
table : 翻译表,通过 maketrans() 方法转换而来
deletechars : 字符串中要过滤的字符列表 - 返回值
返回翻译后的字符串,若给出了 delete 参数,则将原来的bytes中的属于delete的字符删除,剩下的字符要按照table中给出的映射来进行映射
代码示例:
intab = "helow"
outtab = "12345"
trantab = str.maketrans(intab, outtab) # 制作翻译表
str = "hello world!!!"
print(str.translate(trantab))
'''
输出结果:
12334 54r3d!!!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
max(str)
返回字符串 str 中最大的字母
max(str)
- 参数
str : 字符串 - 返回值
返回字符串中最大的字母
代码示例:
str = "Hello World!!!"
print ("最大字符: " + max(str))
'''
输出结果:
最大字符: r
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
min(str)
返回字符串 str 中最小的字母
min(str)
- 参数
str : 字符串 - 返回值
返回字符串 str 中最小的字母
代码示例:
str = "abcdefg"
print ("最小字符: " + min(str))
'''
输出结果:
最小字符: a
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
replace(old, new [, max])
把 将字符串中的 old 替换成 new
如果 max 指定,则替换不超过 max 次
str.replace(old, new[, max])
- 参数
old : 将被替换的子字符串
new : 新字符串,用于替换old子字符串
max : 替换不超过 max 次 - 返回值
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次
代码示例:
str = "1年了"
print("错误码龄:", str)
print("正确码龄:", str.replace("1年", "2年"))
str = "hello hello world!"
print(str.replace("hello", "bye", 2))
str = "hello hello world!"
print(str.replace("hello", "bye", 1))
str = "hello hello world!"
print(str.replace("hello", "bye", 0))
'''
输出结果:
错误码龄: 1年了
正确码龄: 2年了
bye bye world!
bye hello world!
hello hello world!
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
split(str=””, num=string.count(str))
以 str 为分隔符分割字符串,如果 num 有指定值,则仅分割 num+1 个子字符串
str.split(str=””, num=string.count(str))
- 参数
str : 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等
num : 分割次数(默认为 -1, 即分隔所有) - 返回值
返回分割后的字符串列表
代码示例:
str = "hello hello world!"
print (str.split( )) # 以空格为分隔符
print (str.split(' ',1)) # 以 " " 为分隔符
print (str.split(' ',0)) # 以 " " 为分隔符
print (str.split('w')) # 以 w 为分隔符
'''
输出结果:
['hello', 'hello', 'world!']
['hello', 'hello world!']
['hello hello world!']
['hello hello ', 'orld!']
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
splitlines([keepends])
按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表
如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符
str.splitlines([keepends])
- 参数
keepends : 在输出结果里是否去掉换行符(’\r’, ‘\r\n’, \n’),默认为 False,不包含换行符,如果为 True,则保留换行符 - 返回值
返回一个包含各行作为元素的列表
代码示例:
str = 'ab c\n\nde fg\rkl\r\n'
print (str.splitlines()) # 输出结果里去掉换行符('\r', '\r\n', \n')
print (str.splitlines(True)) # 输出结果里包含换行符('\r', '\r\n', \n')
'''
输出结果:
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
isdecimal()
检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false
注意:定义一个十进制字符串,只需要在字符串前添加 ‘u’ 前缀即可
str.isdecimal()
- 参数
无 - 返回值
如果字符串是否只包含十进制字符返回True,否则返回False
代码示例:
str = "hello 2021"
print (str.isdecimal())
str = "2021 2021"
print (str.isdecimal())
str = "20212021"
print (str.isdecimal())
'''
输出结果:
False
False
True
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14