1.字符串是python中不可变数据类型
前一部分字符串的相关操作:
方法名 | 描述说明 |
str.lower() | 将 str 字符串全部转成小写字母,结果为一个新的字符串。 |
str.upper() | 将 str 字符串全部转成大写字母,结果为一个新的字符串。 |
str.split(sep=None) | 把 str 按照指定的分隔符 sep 进行分隔,结果为列表类型。 |
str.count(sub) | 结果为 sub 这个字符串在 str 中出现的次数。 |
str.find(sub) | 查询 sub 这个字符串在 str 中是否存在,如果不存在结果为 -1,如果存在,结果为 sub 首次出现的索引。 |
str.index(sub) | 功能与 find() 相同,区别在于要查询的子串 sub 不存在时,程序报错。 |
str.startswith(s) | 查询字符串 str 是否以子串 s 开头。 |
str.endswith(s) | 查询字符串 str 是否以子串 s 结尾。 |
以上操作的运用:
#大小写转换
s1='HelloWorld'
new_s2=s1.lower()
print(s1,new_s2)
new_s3=s1.upper()
print(new_s3)
#字符串的分割
e_mail='wjl@163.com'
lst=e_mail.split('@')
print('邮箱名:',lst[0],'邮件服务器域名:',lst[1])
#统计函数
print(s1.count('o'))
#检索操作
print(s1.find('o'))
print(s1.find('p'))#-1表示没有找到
print(s1.index('o'))
#print(s1.index('p'))#ValueError: substring not found没有找到并报错
#判断前缀和后缀
print(s1.startswith('H'))
print(s1.startswith('P'))
print('demo.py'.endswith('.py'))
print('text.txt'.endswith('.txt'))
2.后一部分的字符串的相关操作:
方法名 | 描述说明 |
str.replace(old, new) | 使用 new 替换字符串 s 中所有的 old 字符串,结果是一个新的字符串。 |
str.center(width, fillchar) | 字符串 str 在指定的宽度范围内居中,可以使用 fillchar 进行填充。 |
str.join(iter) | 在 iter 中的每个元素的后面都增加一个新的字符串 str。 |
str.strip(chars) | 从字符串中去掉左侧和右侧 chars 中列出的字符串。 |
str.lstrip(chars) | 从字符串中去掉左侧 chars 中列出的字符串。 |
str.rstrip(chars) | 从字符串中去掉右侧 chars 中列出的字符串。 |
以上操作的运用:
s='helloworld'
#字符串的替换
new_s=s.replace('o','你好',1)#最后的那个count参数用来指定第几个为‘你好’,默认是全部替换
print(new_s)
#字符串在指定的宽度范围内居中
print(s.center(20))
print(s.center(20,'*'))#参数fillchar是进行添加什么
#去掉字符串左右的空格
s=' hello world '
print(s.strip())#左右两边都去掉空格
print(s.lstrip())#只去掉左边的空格
print(s.rstrip())#只去掉右边的空格
#去掉指定的字符
s='ld-helloworld'
print(s.strip('ld'))#左右两边都去掉
print(s.lstrip('ld'))#只去掉左边的
print(s.rstrip('ld'))#只去掉右边的
注:代码中有相关操作的说明!!!