數字和字串型別
對字串的操作
有如下變數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
編年齡遊戲
- 編寫猜年齡遊戲,有以下要求:
- 可能會有使用者會在輸入年齡之後不小心輸入空格,如18 ,請做處理
- 可能會有使用者會惡意輸入導致程式報錯,如
逗你玩呀
,請做處理 - 如果使用者3次沒有猜對,可以選擇繼續玩或退出(自定義退出條件)
- 如果使用者猜對了,可以在以下獎品中選擇兩件獎品(一次只能選擇一件獎品):
{0:'toy_car',1:'doll',2:'puzzle'}
- 使用者選擇獎品後退出程式,使用者也可以不選擇獎品直接退出程式。
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