python字符串是基本的数据类型,字符串类内置了多个方法,完成对字符串的不同操作。
环境
- python3.9
- win10 64bit
创建
字符串的创建,可以通过python内置的类str
,也可以使用英文的单引号'
或双引号"
。
str
str
类可以传入一个python对象,从而将其转换为字符串.
# 整数转为字符串
str(123)
'123'
在python3中,很多对象都自带了__str__()
方法,
直接调用就可以转为字符串对象。
# 列表转为字符串
[1,2,'a'].__str__()
"[1, 2, 'a']"
'或"
用引号'
或"
包裹对象可创建字符串。
# 单引号创建字符串
'a123'
'a123'
当字符串中有引号的嵌套情形时,需要混合使用单双引号。
# 单双引号混合
"123'a'456"
"123'a'456"
换行字符串的创建通过三引号'''
或"""
创建。
"""
123
abc
456
"""
'\n123\nabc\n456\n'
查找
index/rindex
index
方法获取子字符串出现的最小位置,rindex
方法获取子字符串出现的最大位置。可约束字符查找的起止位置。当子字符串未查到到时,会报错。
s='hello,python string'
# 字符t的最小位置
s.index('t')
8
# 字符t的最小位置(从索引9后开始查找)
s.index('t',9)
14
# 字符t的最大位置
s.rindex('t')
14
find/rfind
find
方法与index
基本相同,当子字符串未查找到时,不报错,返回-1
。
# 字符t的最小位置
s.find('t')
8
# 字符t的最小位置(从索引9后开始查找)
s.find('t',9)
14
# 字符t的最大位置
s.rfind('t')
14
# 子字符串未查找到
s.find('a')
-1
拼接
join
join
方法可以拼接多个字符串,传入的参数为可迭代对象,如list
,tuple
等。
# 用,拼接多个字符串
','.join(('hello','python'))
'hello,python'
+
使用加号+
可拼接多个字符串。
'python'+','+'python'
'python,python'
计数
count
count
方法计算子字符串的个数,传入参数为子字符串,可约束字符查找的起止位置。
# 计算全部字符l的个数
'hello,list'.count('l')
3
# 计算字符l的个数(从索引3到6之间)
'hello,list'.count('l',3,6)
1
len
__len__()
方法计算字符串的总长度,与内置len()
函数计算结果相同。
# 计算字符串总长度
'hello,python'.__len__()
12
替换
replace
replace
方法替换字符串中的子字符串,可设置替换次数。
# 替换全部
'apple'.replace('p','P')
'aPPle'
# 替换一次
'apple'.replace('p','P',1)
'aPple'
translate
translate
方法用自定义的翻译表替换字符中的某些字符。用maketrans
方法制作翻译表,可使用字典或两个等长的字符串创建。
# 翻译字符串(字典翻译表)
'hello,python3'.translate(str.maketrans({'h':'H','p':'P','3':'3.8'}))
'Hello,PytHon3.8'
# 翻译字符串(字符串翻译表)
'hello,python3'.translate(str.maketrans('hp3','HP2'))
'Hello,PytHon2'
expandtabs
expandtabs
方法用来替换字符串中的制表符\t
为空格,默认替换成8个空格。
# 替换\t为空格(默认8个)
'\taa\tbb\tcc'.expandtabs()
' aa bb cc'
# 替换\t为空格(2个)
'\taa\tbb\tcc'.expandtabs(2)
' aa bb cc'
分割
split/rsplit
split
方法按分隔符(默认空格)分割字符串,可设置分割次数,默认-1
,表示全部分割。rsplit
表示从字符串的
右边开始分割。分割后为list
。
# 全部分割
'a b c'.split()
['a', 'b', 'c']
# 只分割一次
'a b c'.split(maxsplit=1)
['a', 'b c']
# 只分割一次(从右边开始分割)
'a b c'.rsplit(maxsplit=1)
['a b', 'c']
splitline
splitline
方法按换行符\n
,\r
分割字符串。分割后为list
。设置keepends
为True
,可在结果中保留分割符。
# 分割行,不保留分隔符
'abc\n123\rpython'.splitlines()
['abc', '123', 'python']
# 分割行,保留分割符
'abc\n123\rpython'.splitlines(keepends=True)
['abc\n', '123\r', 'python']
partition/rpartition
partition
方法按照分割符分割字符串成为三部分,分割符位置为第一次出现的位置。
rpartition
分割符位置为右边开始的第一个位置。分割后为tuple
。
# 从左边分割
'hello,python,java'.partition(',')
('hello', ',', 'python,java')
# 从右边分割
'hello,python,java'.rpartition(',')
('hello,python', ',', 'java')
删除
strip/lstrip/rstrip
strip
方法删除字符串前后的多个字符(默认空格),lstrip
方法只删除左边字符,rstrip
方法只删除右边字符。
# 删除两边的空格
' hello,python '.strip()
'hello,python'
# 删除两边的-字符
'---hello,python--'.strip('-')
'hello,python'
# 删除左边空格
' hello,python '.lstrip()
'hello,python '
# 删除右边空格
' hello,python '.rstrip()
' hello,python'
removeprefix/removesufix
removeprefix
方法删除字符串的前缀,removesufix
方法删除字符串的后缀。
# 删除前缀
'hello,python'.removeprefix('hello')
',python'
# 删除后缀
'hello,python'.removesuffix('python')
'hello,'
这两个方法与strip
方法不同,它们只删除一次。strip
方法是删除所有能匹配到的字符。
# 只删除第一个p
'ppython'.removeprefix('p')
'python'
# 两个p都删除
'ppython'.lstrip('p')
'ython'
变换
capitalize/lower/upper/swapcase
capitalize
方法把字符串标题化,一般首字母会大写,其他字母小写。lower
方法把大写字母变成小写,upper
方法把小写字母变成大写。swapcase
方法把小写变大写,大写变小写。
# 标题化
'hello,python'.capitalize()
'Hello,python'
# 小写变成大写
'hello'.upper()
'HELLO'
# 大写变成小写
'HELLO'.lower()
'hello'
# 小写变大写,大写变小写
'Python'.swapcase()
'pYTHON'
format/format_map
format
方法格式化方法显示占位符{}
内容,可传入位置参数和关键字参数。format_map
方法传入一个map对象。
'{} was born in {country}'.format('Jack',country='China')
'Jack was born in China'
# format格式化输出
'decimal{:.2f},percentage{:.1%},thousandSeparator{:,}'.format(12.367,0.237,12354)
'decimal12.37,percentage23.7%,thousandSeparator12,354'
# format_map传入map对象格式化字符串
'{name} was born in {country}'.format_map({'name':'Jack','country':'China'})
'Jack was born in China'
填充
center/ljust/rjust
center
方法把字符串放在指定长度的中间,ljust
方法把字符串放在左边,rjust
把字符串放在右边,均可设置填充字符。
# 字符串位于中间,总长度为30
s.center(30)
' hello,python string '
# 字符串位于中间,总长度为30,填充字符为-
s.center(30,'-')
'-----hello,python string------'
# 字符串位于左边,总长度为30,填充字符为-
s.ljust(30,'-')
'hello,python string-----------'
# 字符串位于右边,总长度为30,填充字符为-
s.rjust(30,'-')
'-----------hello,python string'
zfill
zfill
方法在字符串的左边填充0,需要设置字符串总长度。
'abc'.zfill(10)
'0000000abc'
编码
encode/decode
encode
方法把字符编码成字节,decode
方法用于把字节解码成字符。
# 编码成字节
b='中国'.encode()
b
b'\xe4\xb8\xad\xe5\x9b\xbd'
# 解码成字符
b.decode()
'中国'
判断
字符串自带各种判断方法。
startswith/endswith
startswith
方法判断字符串是否以指定字符串开头,endswith
方法用于判断字符串是否以指定字符串结尾,
都可设置字符串判断的起止位置。指定字符串为tuple
时,表示或,可匹配多条件。
# 判断以hello开头
s.startswith('hello')
True
# 判断以hello或者bye开头
s.startswith(('hello','bye'))
True
# 判断以python开头(设置判断开始位置)
s.startswith('python',6)
True
# 判断以string结尾
s.endswith('string')
True
# 判断以string或者bye结尾
s.endswith(('string','bye'))
True
# 判断以python结尾(设置判断结束位置)
s.endswith('python',None,12)
True
isalnum
isalnum
方法判断字符串是否由字母和数据组成。
# 只有字符和数字
'Aa123'.isalnum()
True
# 有,符号
',Aa123'.isalnum()
False
isalpha
isalnum
方法判断字符串是否只由字母组成。
'Aa'.isalpha()
True
'Aa123'.isalpha()
False
isnumeric
isnumeric
方法判断字符串是否只由数字组成。数字包括了unicode数字,罗马数字,汉字数字。识别范围最广。
'123'.isnumeric()
True
# 指数^2
'\u00B2'.isnumeric()
True
# 汉字数字
'五'.isnumeric()
True
# 罗马数字
'Ⅷ'.isnumeric()
True
isdigit
isdigit
方法判断字符串是否只由数字组成。只能识别普通数字和unicode数字。识别范围居中。
'123'.isdigit()
True
'\u00B2'.isdigit()
True
'五'.isdigit()
False
'Ⅷ'.isdigit()
False
isdecimal
isdigit
方法判断字符串是否只由数字组成。只能识别普通数字。识别范围最下。
'123'.isdecimal()
True
'\u00B2'.isdecimal()
False
'五'.isdecimal()
False
'Ⅷ'.isdecimal()
False
isascii
isascii
方法判断字符串是否由ASCII码组成。ASCII字符的码位在 U+0000-U+007F 范围内
'As34>,'.isascii()
True
'中国'.isascii()
False
isidentifier
isidentifier
用来检查字符串是否为有效标识符。如果字符串仅包含字母数字字母(a-z)和(0-9)或下划线(_),
则该字符串被视为有效标识符。有效的标识符不能以数字开头或包含任何空格。
'My_Python09'.isidentifier()
True
# 数字打头不有效
'2string'.isidentifier()
False
# 包含空格不有效
'one two'.isidentifier()
False
islower
islower
方法判断字符串是否都是小写字母。
'letter'.islower()
True
'Letter'.islower()
False
isupper
isupper
方法判断字符串是否都是大写字母。
'LETTER'.isupper()
True
'Letter'.isupper()
False
istitle
istitle
方法判断字符串中的单词是否都是标题形式(首字母大写,其他小写)。
'Hello,Python'.istitle()
True
'Hello,python'.istitle()
False
isspace
isspace
方法判断字符串是否全是空格。
' '.isspace()
True
'a b'.isspace()
False
isprintable
isprintable
方法判断字符串是否可打印。不可打印的字符有换行符\n
,制表符\t
。
'hello,\t'.isprintable()
False
'hello,\n'.isprintable()
False
网友评论