字符串str

py容器List

  1. 操作与list相同
  2. 不含可修改方法

replace

母串.replace(字串1,字串2) - 将母串中含有的字串1换成字串2,并返回一个新的字符串

string = "python"
newstr = string.replace("y", "a")
print(newstr,string) #output:pathon python

split

字符串.split(分隔字符串) - 返回分割后的字符串列表

string = "hello world i am python"
strlist = string.split(" ")
print(strlist)
# output:['hello', 'world', 'i', 'am', 'python']

strip

字符串.strip() - 去除前后空格 字符串.strip(字符串2) - 去除前后指定字符串

string = "      what is love  "
print(string.strip()) #output:"what is love"
 
string = "123what is love321"
print(string.strip("123")) # output:"what is love"
# 按单个字符删除,即母串前后中有'1''2'就删除

join

字符串.join(容器) - 容器为单词,字符串为分隔符,返回新字符串

words = ["blue","is","sky","the"]
words2 = ["blue","is","sky","the"]
print(' '.join(words)) #output:"blue is sky the"
print(''.join(words2)) #output:"blueisskythe"

find

字符串.find(子串) - 字符串中找子串,返回索引值

haystack ="butsad"
needle ="sad"
print(haystack.find(needle)) # output: 3 子串首字母位置下标