用单引号 ' 或双引号 " 括起来,同时使用反斜杠 转义特殊字符;
如果不想转义,可以在字符串前面添加一个 r ;
字符串不能被修改,拼接字符串后,是产生新的字符串;
索引值从左以 0 为开始值,-1 为从末尾的开始位置;
截取的语法格式为:变量[头下标 : 尾下标];
星号 * 表示复制当前字符串;加号 + 是字符串的连接符;
name = 'Hello World!'print(name) # 输出:Hello World!print(name[0]) # 输出:Hprint(name[-1]) # 输出:!print(name[-6:-2]) # 输出:Worlprint(name * 2) # 输出:Hello World!Hello World!print(name + 'Ok!') # 输出:Hello World!Ok!sss = 'HellotPython'print(sss) # 输出:Hello Pythonsss2 = r'HellotPython'print(sss2) # 输出:HellotPython
字符串提供查找、替换、充填等方法,在中可以使用
print(dir('sss'))获取字符串可使用的所有方法。
1、字符串查找
# index(sub[, start[, end]])sss = 'HellotPython'print(sss.index('o')) # 输出:4print(sss.rindex('o')) # 输出:10print(sss.index('o', 0, 5)) # 输出:4# print(sss.index('o',0,4)) # 在[0,4)区间未找到,报错:ValueError: substring not found# print(sss.index('a')) # 若不存在则报错:ValueError: substring not found# find(sub[, start[, end]])print(sss.find('o')) # 输出:4print(sss.rfind('o')) # 输出:10print(sss.find('o', 0, 4)) # 输出:-1print(sss.find('a')) # 输出:-1
2、字符串转换
sss = 'swith alPHA'print(sss.capitalize()) # 输出:Swith alphaprint(sss.title()) # 输出:Swith Alphaprint(sss.swapcase()) # 输出:SWITH ALphaprint(sss.upper()) # 输出:SWITH ALPHAprint(sss.lower()) # 输出:swith alphaprint(sss.casefold()) # 输出:swith alpha
3、字符串填充
sss = 'hello'print(sss.center(16, '-')) # 输出:-----hello------print(sss.ljust(16, '-')) # 输出:hello-----------print(sss.rjust(16, '-')) # 输出:-----------helloprint(sss.zfill(16)) # 输出:00000000000hello
4、字符串检测
参数:
:前缀,可以是单个字符,也可以是字符串
:后缀,可以是单个字符,也可以是字符串
start:索引字符串的起始位置
end:索引字符串的结束位置
返回值:布尔类型(True,False)
sss = 'hello'print(sss.startswith('h')) # 输出:Trueprint(sss.startswith('h',2,3)) # 输出:False 从索引2开始的不是h,所以返回falseprint(sss.endswith('h')) # 输出:Falseprint(sss.endswith('lo')) # 输出:True# 检测是否全由小写字母组成print('Apple 1'.islower()) # 输出:Falseprint('Apple'.islower()) # 输出:Falseprint('apple'.islower()) # 输出:True# 检测是否全由大写字母组成print('Apple'.islower()) # 输出:Falseprint('APPLE'.isupper()) # 输出:True# 检测是否全为标题,即首字母为大写,其它字母为小写print('Apple'.istitle()) # 输出:Trueprint('APPLE'.istitle()) # 输出:False# 检测字符串是否由字母和数字组成print(' '.isalnum()) # 输出:Falseprint('1'.isalnum()) # 输出:Trueprint('h'.isalnum()) # 输出:True# 检测字符串是否只由字母组成。print(' '.isalpha()) # 输出:Falseprint('1'.isalpha()) # 输出:Falseprint('h'.isalpha()) # 输出:True# 检测字符串是否只由数字组成.print(' '.isdigit()) # 输出:Falseprint('1'.isdigit()) # 输出:Trueprint('h'.isdigit()) # 输出:Falseprint('1230'.isdecimal()) # 输出:Trueprint('1230'.isnumeric()) # 输出:True# 检测t n 等转义符print('space and table'.isprintable()) # 输出:Trueprint('spacenandttable2'.isprintable()) # 输出:False# 检测字符串是否只由空格组成。print('space and table'.isspace()) # 输出:Falseprint('spacenandttable2'.isspace()) # 输出:Falseprint(' n t '.isspace()) # 输出:True 转义字符也算# 非标识符:数字开始,和包含非下划线_的其他字符,返回Falseprint('123var '.isidentifier()) # 输出:Falseprint('i@nt'.isidentifier()) # 输出:Falseprint('str'.isidentifier()) # 输出:Trueprint('for'.isidentifier()) # 输出:Trueprint('def'.isidentifier()) # 输出:Trueprint('None'.isidentifier()) # 输出:Trueprint('True'.isidentifier()) # 输出:True
5、字符串裁剪
sss = ' onettwo threet n's1 = sss.strip()print(len(sss)) # 输出:17print(s1,len(s1)) # 输出:one two three 13 前后的空格和t被去掉sss2 = 'abab one ab one ab' # 也可以去除字符串print(sss2.strip('ab')) # 输出:one ab onesss3 = 'aa onettwo a threetaa' # 去除开头或结尾连续相同的字符print(sss3.strip('aa')) # 输出:one two a three 开头多个连续a被去除print(sss3.lstrip('a')) # 输出:one two a three aaprint(sss3.rstrip('a')) # 输出:aa one two a three
6、字符串分割
参数:
sep:分隔符,默认为空格,但不能为空即(")。
:最大分割参数,默认参数为-1。
:在输出结果里是否去掉行界符('r', 'rn', n'等),默认为 False,不包含行界符,如果为 True,则保留行界符。
: 要连接的变量截取字符串,可以是 字符串,元组截取字符串,字典,列表等。中元素必须全部是字符串类型,否则报错。
sss = 'aa onentworarn threetaa's1 = sss.split()print(s1) # 输出:['aa', 'one', 'two', 'a', 'three', 'aa']s2 = sss.split('a')print(s2) # 输出:['', '', ' onentwor', 'rn threet', '', '']s3 = sss.split('a', maxsplit=2) # 最大分割次数2,表示只分2次print(s3) # 输出:['', '', ' onentworarn threetaa']s4 = sss.rsplit('a', maxsplit=2) # 从右开始,最大分割次数2,表示只分2次print(s4) # 输出:['aa onentworarn threet', '', '']s5 = sss.splitlines()print(s5) # 输出:['aa one', 'two', 'a', ' threetaa']s5 = sss.splitlines(keepends=True) # 输出结果中保留换行符print(s5) # 输出:['aa onen', 'twor', 'arn', ' threetaa']s6 = sss.partition('a') # 输出:('', 'a', 'a onentworarn threetaa')print(s6)s6 = sss.rpartition('a') # 输出:('aa onentworarn threeta', 'a', '')print(s6)print('@'.join(s1)) # 输出 :aa@one@two@a@three@aaprint('@'.join(['a',1,'b'])) #TypeError: sequence item 1: expected str instance,
7、其他:统计次数、字符替换、加密字符串
# 统计字符串里某个字符出现的次数;print('one two three'.count('o')) # 输出 :2print('one two three'.count('o', 1)) # 输出 :1# 把字符串中的 old 替换成 new;print('one two three'.replace(' ', '_')) # 输出 :one_two_threeprint('one two three'.replace(' ', '_', 1)) # 输出 :one_two three# 将字符串S中的 t 替换为一定数量的空格print('0t1t2') # 输出 :0 1 2print('0t1t2'.expandtabs(tabsize=5)) # 输出 :0 1 2print('0t1t2'.expandtabs(tabsize=9)) # 输出 :0 1 2# maketrans(intab, outtab,delchars) :返回字符映射表# translate(map_table) :根据映射表输出转换后的字符串intab = 'ABCDE'outtab = '12345'delchars = ' G'map_table = str.maketrans(intab, outtab, delchars)print(map_table) # 输出:{65: 49, 66: 50, 67: 51, 68: 52, 69: 53, 32: None, 71: None}sss = 'Aa BbCcDd EeFfGg'print(sss.translate(map_table)) # 输出:1a2b3c4d5eFfg# 如果给的了delchars,且又配置了映射字符串,则delchars优先级较高,会删除改字符串,而不是转换。delchars = ' GA'map_table = str.maketrans(intab, outtab, delchars)print(map_table) # 输出:{65: None, 66: 50, 67: 51, 68: 52, 69: 53, 32: None, 71: None}sss = 'Aa BbCcDd EeFfGg'print(sss.translate(map_table)) # 输出:a2b3c4d5eFfg
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。