page contents

号外号外......此处有常用字符串操作函数!

有哪些常用的字符串操作函数,一起来看看吧!
  • 字符串操作函数

  • 下面列举了多种常用的字符串操作函数(除了切片)

1.计算字符串长度:len( )

# 常用字符串操作函数
# 1.计算字符串长度:len()
# 空白符、字符、换行符
str1 = ' hello world !\n'
print(len(str1))

2.查找指定字符在字符串中的位置:find( )

# 2.查找指定字符在字符串中的位置:find()
# 索引从0开始,若找不到指定字符,则返回值-1
str2 = 'hello world !\n'
print(str2.find('or'))
print(str2.find('shit'))

3.判断字符串的开头字符:startswith( )

# 3.判断字符串的开头字符:startswith()
str3 = ' hello world !\n'
result1 = str3.startswith('he')
print(result1)
print(str3.startswith(' he'))

4.判断字符串的开头字符:endswith( )

# 4.判断字符串的开头字符:endswith()
str4 = ' hello world !\n'
print(str4.endswith('!'))
print(str4.endswith('\n'))

5.将字符串以指定宽度居中,其余部分以特定字符填充

# 5.将字符串以指定宽度居中,其余部分以特定字符填充
# center(指定长度,‘特定字符’)
str5 = 'hello world!'
print(str5.center(50, '*'))

6.将字符串以指定宽度放在两侧,其余部分以特定字符填充

# 6.将字符串以指定宽度放在右侧,其余部分以特定字符填充
# rjust(指定长度,‘特定字符’)
# 6.将字符串以指定宽度放在左侧,其余部分以特定字符填充
# ljust(指定长度,‘特定字符’)
str6 = 'hello world!'
print(str6.rjust(50, '*'))
print(str6.ljust(50, '*'))

7.判断字符串由什么组成

# 7.判断字符串由什么组成
# 1.isdigit():判断字符串是否由数字组成
# 2.isalpha():判断字符串是否由字母组成
# 3.isalnum():判断字符串是否由数字和字母组成
str7 = '1234abcd'
print(str7.isdigit())
print(str7.isalpha())
print(str7.isalnum())

8.删除字符串中的空白

# 8.删除字符串中的空白
# 1.lstrip():删除字符串左边的空白
# 2.rstrip():删除字符串右边的空白
# 3.strip():删除字符串两边的空白
str8 = ' Python   '
print(str8)
print(str8.lstrip())
print(str8.rstrip())
print(str8.strip())

9.字符串的切片

# 9.字符串的切片
# 可以选取字符串指定位置的字符:str1[4]
# 可以选取字符串中连续的一段:str1[1:4] 右端不包括在查找范围之内
# 可间断选取字符串中字符:str1[0::2] 其中2为步长,:代表直到最后
# 可以将字符串倒序:str1[::-1] 负数步长代表从后向前查找
str9 = '1234abcd'
print(str9[4])
print(str9[1:4])
print(str9[0::2])
print(str9[::-1])

  • 发表于 2021-04-30 21:20
  • 阅读 ( 606 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Cara
Cara

36 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1312 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章