Python练习10-Eric
#第一种方法思路:#将字符串以空格分割成列表
#遍历列表中的字符串,输出长度小于等于6的元素
strs="I am oldboy teacher welcome to oldboy training class."
strs2=strs.strip(".") #str.strip("."),删除字符串首尾的“.”
lists=strs2.split( ) #字符串以空格分割成列表
for i in range(len(lists)): #遍历列表
s=lists #得到单个元素
if len(s)<=6: #判断元素长度
print(s)
print('''
##################第二种方法分割线###################
''')
# 统计字符串中空格的个数
# 找到空格对应的下标n,当n<=6,则第一个空格之前的字符串就是我们想要的;
# 然后将切片,再次循环上述操作;
# 最后剩下的一个字符串"class",单独比较长度后选择输出
strs="I am oldboy teacher welcome to oldboy training class."
strs2=strs.strip(".")
m=(strs2.count(" ")) # 统计字符串中空格的个数
for i in range(m):
n=strs2.find(" ") #找到空格对应的下标n
if 0<n<=6: #当n<=6,则第一个空格之前的字符串就是我们想要的:
print(strs2) #即
strs2=strs2 #将切片,再次循环上述操作;
if len(strs2)<=6: #最后一个字符串,判断长度
print(strs2)
页:
[1]