【Python】字符串操作方法

一、下标

在Python中每个字符串都会被分配下标,下标标识从0开始,类似于Java中的数组。

二、切片

语法:序列[开始下标:结束下标:步长]

str1 = '012345678'
print(str1[2:5:1])

输出结果为:234

当开始下标和结束下标为负数时,字符串最后一个字符下标为-1,即8下标为-1。

str1 = '012345678'
print(str1[-4:-1:1])

输出结果为:567

当步长为-1时,字符串从最后一个字符开始输出。

str1 = '012345678'
print(str1[::-1])

输出结果为:876543210

三、查找

  • find ():检查某个子串是否包含在字符串中,如果有则返回该子串开始的位置下标否则返回-1。

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

mystr = 'Hello World and itcast and SamRol and Python'

print(mystr.find('and'))#12
print(mystr.find('and', 15, 30))#23
print(mystr.find('ands')) #-1
  • rfind():和find()功能相同,但查找方向为右侧。

  • index():和find()功能相同主要用于列表,但查找失败会报错。

  • rindex():和index()功能相同,但查找方向为右侧开始。

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

  • len():访问列表的长度,即列表中数据的个数。

四、修改

  • replace()​​​​​​

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

替换:原有的字符串不会被修改。

str1 = 'Hello Word and itcast and SamRol and Python'

new_str1 = str1.replace('and', 'he')

print(str1)
print(new_str1)
  • split()

分割:返回一个列表,删除指定字符。

语法字符串序列.split(分割字符, 次数)

mystr = 'Hello World and itcast and SamRol and Python'

split1 = mystr.split('and', 3)
  • join()

​​合并:用一个字符或子串合并成字符串,即将多个字符串合并成一个新的字符串。

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

mylist = ['aa','bb','cc']

newlist = '...'.join(mylist)

print(newlist)

输出结果为:aa...bb...ccc

五、大小写转换

  • capitalize():将字符串第一个字符转换成大写。

  • title():将字符串每个单词的首字母转换成大写。

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

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

str1 ='abc'

str2 = str1.title()

print(str2)

六、删除空白字符

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

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

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

str1 = '      abc'

str2 = str1.lstrip()

print(str2)

七、对齐

  •  ljust(长度,填充字符):返回一个原字符串左对齐,并使用指定字符填充至指定长度的新字符串。

  • rjust()

  • center()

str1 = 'abc'

str2 = str1.ljust(6, '.')

print(str2)

#输出结果为:abc...

八、判断

  • ​​​startswith():检查字符串是否以指定子串开头,有则返回true无侧返回false,如果设置上标和下标,则在指定范围内查找。

  • endswith():与上函数类似。

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

str1 = 'abc ace dab ced'

print(str1.startswith('ace', 3, 7))

#输出结果为:true
  • isalpha():如果字符串至少有一个字符,并且所有字符都是字母则返回true,否则返回false。

  • isdigit():如果字符串只包含数字则返回true,否则返回false。

  • isalnum():如果字符串至少有一个字符,并且所有字符都是字母或数字则返回true,否则返回false。

  • isspace():如果字符串中只包含空白则返回true,否则返回false。

str1 = 'abc'

print(str1.isalpha())

猜你喜欢

转载自blog.csdn.net/qq_26082507/article/details/120606751