字符串常见操作
my_str = 'hello world neuedu and neueducpp'
- find()
检查str 中是否包含在 my_str中,如果在返回开始的索引值,否则返回-1
index1 = my_str.find('neuedu')
print(index1)
index2 = my_str.find('neuedu', 0 , 10)
print(index2)
- index()
跟find()一样 只不过str不在mystr中要报一个异常
index3 = my_str.index('neuedu', 0 , 10)
print(index3)
- count 返回 目标字符串出现的次数
count = my_str.count('neuedu',0, 20)
print(count)
- replace
¥599 ------> 599
name = 'hello world haha'
new_name = name.replace('ha', 'Ha')
print(new_name)
name = 'hello world haha'
new_name = name.replace('ha', 'Ha', 1)
print(new_name)
price = "¥599"
price = price.replace('¥', '')
print(price)
- split()
以str为分隔符分割name,如果maxsplit指定值,那么仅分割maxsplit个子串
name = 'hello world ha ha'
name_list = name.split(" ")
print(name_list)
name_list1 = name.split(" ", 2)
print(name_list1)
- capitalize()把字符串的一个字符大写
my_str2 = my_str.capitalize()
print(my_str2)
- title() 把字符串的每个单词首字母大写
my_str3 = my_str.title()
print(my_str3)
- startswith 检测字符串是否以str为开头
my_str4 = my_str.startswith('hello')
print(my_str4)
my_str5 = my_str.startswith('Hello')
print(my_str5)
- endwith() 检测字符串是否以str为结尾
my_str6 = my_str.endswith('cpp')
print(my_str6)
- upper 把字符串的所有变为大写
my_str7 = my_str.upper()
print(my_str7)
- lower 字符串的所有变为小写
my_str8 = my_str7.lower()
print(my_str8)
- rjust 返回一个原字符串右对齐的并用空格填充 width长度的新字符串
my_str_space = 'hello'
new_my_str_space = my_str_space.rjust(10)
print(new_my_str_space)
- ljust 返回一个原字符串左对齐对对齐的并用空格填充 width长度的新字符串
new_my_str_space1 = my_str_space.ljust(100)
print(new_my_str_space1)
print(len(new_my_str_space1)) - center()
new_my_str_space2 = my_str_space.center(50)
print(new_my_str_space2)
print(len(new_my_str_space2))
- lstrip 清除字符串左边的空白字符
print(new_my_str_space2)
print(len(new_my_str_space2)) # 50
new_str2 = new_my_str_space2.lstrip()
print(len(new_str2))
print(new_str2)
- rstrip()清除字符串右边的空白字符
new_str3 =new_str2.rstrip()
print(len(new_str3)) # 5
print(new_str3)
- strip() 删除两端的空白字符
str1 = '\n\tdadadad\t'
print(len(new_my_str_space2))
new_str4 = new_my_str_space2.strip()
print(len(new_str4))
print(len(str1))
str2 = str1.strip()
print(len(str2))
- find ---> rfind
index5 = my_str.rfind('neuedu')
print(index5)
- rindex ------> index
- partition 把mystr以str分割成3部分 str前,str str后
print(my_str)
t_mystr = my_str.partition('neuedu')
print(t_mystr) # 元组
- rpartition 从右边开始把mystr以str分割成3部分 str前,str str后
- splitlines 按照行分隔,返回一个包含各行作为元素的列表
line = 'hello\nworld'
print(line)
list_line = line.splitlines()
print(list_line)
- isalpha 判断字符串是否都是字母 True
alpha = my_str.isalpha()
print(alpha)
alpha2 = 'dddddddd'
alpha3 = alpha2.isalpha()
print(alpha3)
- isdigit
- isalnum 判断是否只有字母或者数字
alpha2.isalnum() - isspace
- join()
str4 = " "
list1 = ['my','name','is','songxiaobao']
my_name = str4.join(list1)
print(my_name)
_ / ,
my_name = ",".join(list1)
print(my_name)
常用的find count replace split join strip