6.字符串类型和年龄游戏的升级

数字和字符串类型

对字符串的操作

有如下变量name = " aleX",请按照要求实现每个功能:

1. 移除 name 变量对应的值两边的空格,并输出处理结果
2. 判断 name 变量对应的值是否以 "al" 开头,并输出结果
3. 判断 name 变量对应的值是否以 "X" 结尾,并输出结果
4. 将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
5. 将 name 变量对应的值根据 “l” 分割,并输出结果。
6. 将 name 变量对应的值变大写,并输出结果
7. 将 name 变量对应的值变小写,并输出结果
8. 请输出 name 变量对应的值的第 2 个字符?
9. 请输出 name 变量对应的值的前 3 个字符?
10. 请输出 name 变量对应的值的后 2 个字符?
11. 请输出 name 变量对应的值中 “e” 所在索引位置?
12. 获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo
name = " aleX"
print(name.strip())
aleX
print(name.startswith('al'))
False
print(name.endswith('X'))
print(name.replace('l','p'))
print(name.split('l'))
print(name.upper())
print(name.lower())
print(name[1])
print(name[:3])
print(name[-2:])
print(name.find('e'))
print(name.rstrip('X'))
True
 apeX
[' a', 'eX']
 ALEX
 alex
a
 al
eX
3
 ale

编年龄游戏

  1. 编写猜年龄游戏,有以下要求:
    1. 可能会有用户会在输入年龄之后不小心输入空格,如18   ,请做处理
    2. 可能会有用户会恶意输入导致程序报错,如逗你玩呀,请做处理
    3. 如果用户3次没有猜对,可以选择继续玩或退出(自定义退出条件)
    4. 如果用户猜对了,可以在以下奖品中选择两件奖品(一次只能选择一件奖品):{0:'toy_car',1:'doll',2:'puzzle'}
    5. 用户选择奖品后退出程序,用户也可以不选择奖品直接退出程序。
real_age = 18
count =1
while count<=3:
    age = input("please enter the age").strip()
    if age.isdigit():
        if int(age) == 18:
            print('congratulations!')
            for i in range(2):
                prize_dict = {0:'toy_car',1:'doll',2:'puzzle'}
                print(f'please choose one of these gifts: {prize_dict}')
                prize = input('please enter the num:')
                if prize == 'N' or prize == 'n':
                    count = 5
                    break
                print(f'Congratulations, you have received this gift,the gift is {prize_dict[int(prize)]}')
            break
        else:
            print("sorry,guess wrong")
            if int(age) >18:
                print("sorry,guess older")
            else:
                print("sorry,guess younger")
    else:
        print(f'your age is {age}?')
    count +=1
    if count == 4:
        chance = input("please choose you should continue play this game<<<")
        if chance == 'Y'or chance =='y':
            count =1
        elif chance == 'N'or chance =='n':
            break
        else :
            print('please make sure your input is correct')
please enter the age18
congratulations!
please choose one of these gifts: {0: 'toy_car', 1: 'doll', 2: 'puzzle'}
please enter the num:0
Congratulations, you have received this gift,the gift is toy_car
please choose one of these gifts: {0: 'toy_car', 1: 'doll', 2: 'puzzle'}
please enter the num:1
Congratulations, you have received this gift,the gift is doll

posted @ 2024-09-02 16:48  小方呀0524  阅读(31)  评论(0编辑  收藏  举报