python字符串切片常用方法有哪些

编辑: admin 分类: python 发布时间: 2023-05-01 来源:互联网

一、切片

切片:指对操作的对象截取其中一部分的操作,字符串、列表、元组都支持切片操作

语法:序列[开始位置下标:结束位置下标:步长] ,不包含结束位置下标数据,步长为选取间隔,正负均可,默认为1

举例如下:

str = 'abcdefg_a'
print(str[1:6:2], str[2:6], str[:3], str[3:], str[:])
print(str[::2], str[:-2], str[-6:-2], str[::-2], str[::-1])
print(str[-2:], str[2:-2], str[-2::-2], str[:-2:2], str[2:-2:2])
 
输出:
bdf cdef abc defg_a abcdefg_a
acega abcdefg defg ageca a_gfedcba
_a cdefg _fdb aceg ceg
登录后复制

二、常用方法

2.1 查找

查找字符串:即查找子串在字符串中的位置或出现的次数

  • find():检测某个字串是否包含在某个字符串中,若存在则返回该子串开始位置下标,否则返回-1

  • 语法:字符串序列.find(子串,开始位置下标,结束位置下标)

  • index():检测某个子串是否包含在某个字符串中,若存在则返回该子串开始位置下标,否则报异常

    • 语法:字符串序列.index(子串,开始位置下标,结束位置下标)

  • rfind():和find()功能相同,但查找方向为右侧开始,即返回子串最后出现位置

  • rindex():和index()功能相同,但查找方向为右侧开始,即返回子串最后出现位置

  • count():返回某个子串在字符串中出现的次数

举例如下:

str = 'abcdefg_a'
print('-------------------查找-------------------')
print(str.find('c'), str.find('fg', 2, ), str.find('a', 2), str.find('h'))
print(str.index('c'), str.index('fg', 2, ), str.index('a', 2))
print(str.find('a'), str.rfind('a'), str.index('a'), str.rindex('a'), str.count('a'))
print(str.index('h'))
 
输出:
-------------------查找-------------------
2 5 8 -1
2 5 8
0 8 0 8 2
ValueError: substring not found
登录后复制

2.2 修改

修改字符串:通过函数形式修改字符串中的数据

  • replace():替换

    • 语法:字符串序列.replace(旧子串,新子串,最大替换次数)

  • split():按指定字符分割字符串

    • 语法:字符串序列.split(分割字符,分割次数) # 返回数据个数为分割次数+1

  • join():用一个字符或子串合并字符串,即将多个字符串合并为一个新的字符串

    • 语法:字符或子串.join(多字符串组成的序列)

  • capitalize():将字符串第一个字符转为大写,转换后仅首字符大写,其余均小写

    • 语法:字符串序列.capitalize()

  • title():将字符串每个单词首字母转为大写

  • lower():将字符串中大写转小写

  • upper():将字符串中小写转大写

  • swapcase():翻转字符串中大小写

  • partition('分隔符'):根据指定分隔符将字符串分割,返回三元元组,组成为左子串、分隔符、右子串

  • min(str):返回字符串str中最小字母

  • max(str):返回字符串str中最大字母

  • zfill(width):输出指定长度为width的字符串,右对齐,不足前面补0,超出指定长度则原样输出

  • lstrip():删除字符串左侧空格字符

  • rstrip():删除字符串右侧空格字符

  • strip():删除字符串两侧空格字符

  • ljust():字符串左对齐,并用指定字符(默认空格)填充至对应长度

    • 语法:字符串序列.ljust(长度,填充字符)

  • rjust():字符串右对齐,并用指定字符(默认空格)填充至对应长度

    • 语法:字符串序列.rjust(长度,填充字符)

  • center():居中对齐,并用指定字符(默认空格)填充至对应长度

    • 语法:字符串序列.center(长度,填充字符)

举例如下:

print('--------------修改--------------')
str1 = 'hello python and hello IT and hello world and hello YX !'
print(str1.replace('and','&&'))
print(str1.split('and'), str1.split('and', 2))
l = ['Hello', 'world', '!']
t = ('Hello', 'python', '!')
print('_'.join(l), ' '.join(t))  # 用下划线_和空格连接
print(str1.capitalize())  # 首字符转为大写,其余均小写
print(str1.title())  # 每个单词首字母转为大写
str2 = '   Hello World !   '
print(str2.lower(), str2.upper(), str2.swapcase())  # 大写转小写,小写转大写,翻转大小写
print(str2.partition('rl'), str2.partition('o'))  # 根据指定分隔符将字符串分割,返回三元元组
print(min(str2), max(str2), ord(min(str2)), ord(max(str2)))  # str2中最小为空格对应十进制32,最大为r对应114
print(str2.zfill(21))  # 输出指定长度为21的字符串,右对齐,不足前面补0,超出指定长度则原样输出
print(str2.lstrip(), str2.rstrip(), str2.strip())  # 清除字符串左、右、两边空格字符
str3 = 'hello!'
print(str3.ljust(13, '*'), str3.rjust(13, '*'), str3.center(14, '*'))
 
输出:
--------------修改--------------
hello python && hello IT && hello world && hello YX !
['hello python ', ' hello IT ', ' hello world ', ' hello YX !'] ['hello python ', ' hello IT ', ' hello world and hello YX !']
Hello_world_! Hello python !
Hello python and hello it and hello world and hello yx !
Hello Python And Hello It And Hello World And Hello Yx !
   hello world !       HELLO WORLD !       hELLO wORLD !   
('   Hello Wo', 'rl', 'd !   ') ('   Hell', 'o', ' World !   ')
  r 32 114
00   Hello World !  
Hello World !       Hello World ! Hello World !
hello!******* *******hello! ****hello!****
登录后复制

2.3 判断

  • startswith():检查字符串是否以指定子串开头,若是返回True,否则返回False,设置开始和就结束位置下标,则在指定范围内检查

    • 语法:字符串序列.startswith(子串,开始位置下标,结束位置下标)

  • endswith():检查字符串是否以指定子串结尾,是返回True,否则返回False,设置开始和就结束位置下标,则在指定范围内检查

    • 语法:字符串序列.endswith(子串,开始位置下标,结束位置下标)

  • isalpha():若字符串至少有一个字符并所有字符都是字母则返回True,否则返回False

  • isdigit():若字符串只包含数字则返回True否则返回False

  • isalnum():若字符串至少有一个字符且所有字符都是字母或数字则返回True,否则返回False

  • isspace():若字符串只包含空格,则返回True,否则返回False

举例如下:

print('---------------判断----------------')
str3 = 'hello!'
print(str3.startswith('he'), str3.startswith('she'), str3.startswith('he',2,))
print(str3.endswith('!'), str3.endswith('。'), str3.endswith('!', 2, 5))
print(str3.isalpha(),str3.isalnum(), str3.isdigit(), str3.isspace())
 
输出:
---------------判断----------------
True False False
True False False
False False False False
登录后复制

以上就是python字符串切片常用方法有哪些的详细内容,更多请关注海外IDC网其它相关文章!

【文章转自台湾大带宽服务器 http://www.558idc.com/tw.html提供,感恩】