Python——字符串小練習

題目要求1

判斷輸入的變量名是否合法:
1. 變量名可以有字母、數字或者下劃線組成
2. 變量名只能以字母或者下劃線開頭

代碼示例:

while True:
    s = input('Str:')
    if s == 'exit':
        print('logout')
        break     ##退出循環
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
            if not (i.isalnum or i =='_'):
                print('illegal')
                break
        else:
            print('OK')
    else:
            print('illegal')

運行結果

Str:we_hah
OK
Str:12we
illegal
Str:we_kk123
OK
Str:exit
logout

題目要求2

給定一個字符串來代表一個學生的出勤記錄,這個記錄僅包含以下三個字符>:
'A'  : Absent ,缺勤
'L'  : Late , 遲到
'P'  : Present , 到場
如果一個學生的出勤記錄中不超過一個'A'並且不超過兩個連續的'L',那麼這個學生會被獎賞。
你需要根據這個學生的出勤記錄判斷他是否會被獎賞:
示例1:
輸入: “PPALLP”
輸出: “True”
示例2:
輸入: “PPALLL”
輸出: “False

代碼示例

while True:
    s = input('recoder:')
    if  s == 'exit':
        print('logout')
        break    ##退出循環
    elif s.count('A') <= 1 and  s.count('LLL') == 0:
        print('True')
    else:
        print(False)

運行結果

recoder:PPALLL
False
recoder:PPLLA
True
recoder:exit
logout

題目要求3

給定一個句子(只包含字母和空格),將句子中的單詞位置反轉,單詞用空格分割,單詞之間只有一個空格,前後沒有空格。
比如:"hello  xiao mi"---->"mi xiao hello"
--輸入描述:
>輸入數據有多組,每組佔一行,包含一個句子
--輸出描述:
>對於每個測試示例,要求輸出句子中單詞反轉後形成的句子

代碼示例

while True:
    s = input('輸入:\n')
    if s == 'exit':
        print('logout')
        break
    li = s.split()
    print('輸出:')
    print(' '.join(li[::-1]))

運行結果

輸入:
hello xiao mi
輸出:
mi xiao hello
輸入:
hello my friend
輸出:
friend my hello
輸入:
exit
logout
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章