字符串方法梳理:
- endswith(suffix[, start[, end]])
Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position
如果字符串以指定后缀(stuffix)结尾,则为True,反之为False。
- find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end].
返回字符串中需找出的子字符串的最低索引值,即[start:end]中start的索引
- split(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string.
以sep为分隔符,返回字符串中的单词列表
a girl come in, the name is Jack, level 955
其中the name is 后面跟人名,随后紧跟逗号,这是唯一固定格式。实现函数getName获取人名并返回
方法一
def getName(srcStr):
b = a.split("the name is ")[1]
#以"the name is"分割,取列表[1]
srcStr = b.split(',')[0]
#以逗号分割,取列表[0]
return srcStr
解析:
以”a girl come in, the name is Jack, level 955”字符串为例,把固定格式“the name is ”当做分隔符,返回列表[“a girl come in,”,” jack, level 955”],取值list[1] 即“ jack, level 955”。之后再以“,”为分隔符,返回列表,取list[0]并返回
方法二
def getName(srcStr):
b = a.find("the name is")
c = int(b) + 12
d = a.find(",",b)
return srcStr[c:d]
解析:
取”the name is “的开头索引,确定位置,然后加上”the name is “的长度,得到的值即为名字第一位的索引值c;之后,因为名称并不固定,但是名称之后的“,” 是固定的,所以取出逗号的索引,用find()方法在c之后查找逗号的索引d,最后用切片[c:d]取出名字
inputString = input('enter your message:')
a = inputString.split(";")
print(len(a))
for one in a:
if "," not in one:
continue
#遍历每一个元素,进行过滤
name,age = one.split(",")
name = name.strip()
age = age.strip()
#过滤内部无输入信息
if not age.isdigit(): #判断age
continue
if name == "": #判断name
continue
print("%-20s :%02d" % (name,int(age)))
1. 创建一个新的列表newList
2. 先找出所有元素中最小的,append在newList里面
3. 再找出剩余的所有元素中最小的,append在newList里面
4. 依次类推,直到所有的元素都放到newList里面
list1 = [40,1,8,2,7,82,-3,0,]
newlist = []
def mySort(alist):
while alist:
for one in range(len(alist)-1):
if alist[one] < alist[one+1]:
alist[one],alist[one+1] = alist[one+1],alist[one]
newlist.append(alist[-1])
del alist[-1]
return newlist
print(mySort(list1))
#返回字符串元素数量
len(string)
#返回从开始到结束,子字符串出现的次数
str.count(sub[, start[, end]])
#字符串在指定范围内以设置字符结尾,返回True,否则返回False
str.endswith(suffix[, start[, end]])
#字符串在指定范围内以设置字符开头,返回True,否则返回False
str.startswith(suffix[, start[, end]])
#返回从开始到结束,被查询子字符串的最低索引,没找到返回-1
str.find(sub[, start[, end]])
#类似find(),没找到返回ValueError
str.index(sub[, start[, end]])
#如果字符串中所有字符都是数字,返回True,否则返回False
str.isdigit()
#返回通过指定字符(str)连接序列中元素后生成的新字符串
str.join(iterable)
#返回将字符串中所有大小写都变成小写的字符串副本
str.lower()
#返回将字符串中所有大小写都变成大写的字符串副本
str.upper()
#返回所有单词都以大写开始的字符串
str.title()
#返回一个清掉字符串左边空格的字符串副本
str.lstrip([chars])
#返回一个清掉字符串右边空格的字符串副本
str.rstrip([chars])
#返回一个清掉字符串左右两边空格的字符串副本
str.strip([chars])
#返回一个字符串列表,以seq为分隔符
str.split(sep=None, maxsplit=-1)
#返回字符串的行列表,以行边界划分
str.splitlines([keepends])