python day 11,几个关于切片循环的小题目

耗时3小时,未得真谛

# 全是字符串的
# 用于训练考察基本的编程能力
#
# 用到的知识主要是
# 0, 用下标引用字符串
# 1, 字符串切片
# 2, 循环
# 3, 选择 (也就是 if)


# 1,
# 实现一个函数
# 返回一个「删除了字符串开始的所有空格」的字符串
def strip_left(s):
    for i in s:
        if i == ' ':
            print()
            s = s[s.find(i) + 1:]
        else:
            break

    return s


print(strip_left('    hello world '))


#
# 2,
# 实现一个函数
# # 返回一个「删除了字符串末尾的所有空格」的字符串
def strip_right(s):
    for i in range(len(s)):
        if s[-1] == ' ':
            s = s[:-2]
        else:
            break
    return s


print(strip_right('    hello world    '))


# print(strip_left("hell     "))

# 3,

# 返回一个「删除了字符串首尾的所有空格」的字符串
def strip(s):
    s = strip_right(strip_left(s))
    return s


print(strip("   hello  "))


#
# 4,
# 实现一个函数, 接受一个参数 s
# 检查这个参数是否只包含空格
# 返回 True / False
def is_space(s):
    for i in s:
        if i == ' ':
            is_only_space = False
        else:
            is_only_space = True
            break
    return is_only_space


print(is_space('     '))


# 5,
# 实现一个函数, 接受一个参数 s
# 检查这个参数是否只包含 空白符号
# 空白符号包括三种 ' ' 'n' 't'
# 返回 True / False
def is_white(s):
    for i in s:
        if i == ' ' or i == 'n' or i == 't':
            is_only_white = False
        else:
            is_only_white = True
            break
    return is_only_white


# 6,
# 实现一个函数, 接受 2 个参数 s1 s2
# 检查 s1 是否以 s2 开头
# 返回 True / False
def starts_with(s1, s2):
    if s1[:len(s2)] == s2:
        return True
    else:
        return False


print(starts_with('1233', '12'))


# 例子
# print(starts_with('hello', 'he'))
# # True
#
#
# 7,
# 实现一个函数, 接受 3 个参数 s old new 都是字符串
# 返回一个「将 s 中的 old 字符串替换为 new 字符串」的字符串
# 假设 old 存在并且只出现一次
def replace(s, old, new):
    s = s[:s.find(old)] + new + s[s.find(old) + len(old):]
    return s


# 例子
print(replace('hello, world!', 'world', 'gua'))


# # 'hello, gua!'
# 提示: 查找切片 2 次
#
#
# 8,
# 实现一个函数, 接受两个参数 s1 s2 都是字符串
# 返回一个数字, 这个数字是 s2 在 s1 中出现的下标
# 如果不存在则返回 -1
def index(s1, s2):

    # 提示
    # 循环切片加 starts_with
    for l in range(len(s1)):
        print(s1[l:])
        if starts_with(s1[l:],s2):
            return l
            break
        else:
            continue
print(index('13243343444','3'))
#
#
# 9,
# 实现一个函数, 接受 2 个参数 s1 s2 都是字符串
# 返回一个列表,列表中保存了所有 s2 出现在 s1 中的下标
def indices(s1, s2):
    request = []
    for i in range(len(s1)):
        if starts_with(s1[i:], s2):
            request.append(i)
        else:
            continue
    return request

print(indices('13243343444','3'))

# 例子
# # 01234567
# print(indices('12211341', '1'))
# # [0, 3, 4, 7]
#
# 提示: 使用 index 函数加循环

你可能感兴趣的:(python day 11,几个关于切片循环的小题目)