字符串操作函数
下面列举了多种常用的字符串操作函数(除了切片)
# 常用字符串操作函数
# 1.计算字符串长度:len()
# 空白符、字符、换行符
str1 = ' hello world !\n'
print(len(str1))
# 2.查找指定字符在字符串中的位置:find()
# 索引从0开始,若找不到指定字符,则返回值-1
str2 = 'hello world !\n'
print(str2.find('or'))
print(str2.find('shit'))
# 3.判断字符串的开头字符:startswith()
str3 = ' hello world !\n'
result1 = str3.startswith('he')
print(result1)
print(str3.startswith(' he'))
# 4.判断字符串的开头字符:endswith()
str4 = ' hello world !\n'
print(str4.endswith('!'))
print(str4.endswith('\n'))
# 5.将字符串以指定宽度居中,其余部分以特定字符填充
# center(指定长度,‘特定字符’)
str5 = 'hello world!'
print(str5.center(50, '*'))
# 6.将字符串以指定宽度放在右侧,其余部分以特定字符填充
# rjust(指定长度,‘特定字符’)
# 6.将字符串以指定宽度放在左侧,其余部分以特定字符填充
# ljust(指定长度,‘特定字符’)
str6 = 'hello world!'
print(str6.rjust(50, '*'))
print(str6.ljust(50, '*'))
# 7.判断字符串由什么组成
# 1.isdigit():判断字符串是否由数字组成
# 2.isalpha():判断字符串是否由字母组成
# 3.isalnum():判断字符串是否由数字和字母组成
str7 = '1234abcd'
print(str7.isdigit())
print(str7.isalpha())
print(str7.isalnum())
# 8.删除字符串中的空白
# 1.lstrip():删除字符串左边的空白
# 2.rstrip():删除字符串右边的空白
# 3.strip():删除字符串两边的空白
str8 = ' Python '
print(str8)
print(str8.lstrip())
print(str8.rstrip())
print(str8.strip())
# 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])
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!