1.輸入一個字符串,打印所有奇數(shù)位上的字符(下標(biāo)是1,3,5,7…位上的字符),例如: 輸入'abcd1234 ' 輸出'bd24'
str1 = 'abcdef123opq12'
for n in range(1, len(str1), 2):
print(str1[n], end='')
2.輸入用戶名,判斷用戶名是否合法(用戶名長度6~10位)
str1 = '84802-'
n = len(str1)
if 6<= n <=10:
print('用戶名合法')
else:
print('用戶名不合法')
3.輸入用戶名,判斷用戶名是否合法(用戶名中只能由數(shù)字和字母組成) 例如: 'abc' — 合法 '123' — 合法 ‘a(chǎn)bc123a’ — 合法
str1 = '84802--'
for item in str1:
if not('a' <= item <= 'z' or 'A' <= item <= 'Z' or '0' <= item <= '9'):
print('不合法')
break
else:
print('合法')
4.輸入用戶名,判斷用戶名是否合法(用戶名必須包含且只能包含數(shù)字和字母,并且第一個字符必須是大寫字母。例如: 'abc' — 不合法 '123' — 不合法 'abc123' — 不合法 'Abc123ahs' — 合法
str1 = 'Aa1aa' # user_name
if 'A' <= str1[0] <= 'Z':
count = 0 # 統(tǒng)計數(shù)字字符個數(shù)
for item in str1[1:]:
if 'A' <= item <= 'Z' or 'a' <= item <= 'z' or '0' <= item <= '9':
if '0' <= item <= '9':
count += 1
else:
print('不合法')
break
else:
if count > 0:
print('合法')
else:
print('不合法')
else:
print('不合法')
5.輸入一個字符串,將字符串中所有的數(shù)字字符取出來產(chǎn)生一個新的字符串。例如:輸入'abc1shj23kls99+2kkk' 輸出:'123992'
str1 = 'abc1shj23kls99+2kkk'
for item in str1[::1]:
if '0' <= item <= '9':
print(item, end='')
6.輸入一個字符串,將字符串中所有的小寫字母變成對應(yīng)的大寫字母輸出。例如: 輸入'a2h2klm12+' 輸出 'A2H2KLM12+'
str1 = '22HHHa2h2klm12+'
for item in str1[::1]:
if 'a' <= item <= 'z':
print(item.swapcase(),end='')
else:
print(item, end='')
7. 輸入一個小于1000的數(shù)字,產(chǎn)生對應(yīng)的學(xué)號。例如: 輸入'23',輸出'py1901023' 輸入'9', 輸出'py1901009' 輸入'123',輸出'py1901123'
num = 33
study_id = 'py1901' + str(num).zfill(3)
print(study_id)
8.輸入一個字符串,統(tǒng)計字符串中非數(shù)字字母的字符的個數(shù)。例如: 輸入'anc2+93-sj胡說' 輸出:4 輸入'===' 輸出:3
str1 = 'Mn22+\-*43c'
count = 0
for item in str1[::1]:
if not('0' <= item <= '9' or 'a' <= item <= 'z' or 'A' <= item <= 'Z'):
count += 1
print(count)
9.輸入字符串,將字符串的開頭和結(jié)尾變成'+',產(chǎn)生一個新的字符串。例如: 輸入字符串'abc123', 輸出'+bc12+'
str1 = '543cc37k'
a = str1[0]
b = str1[-1]
new_str = str1.replace(a, '+')
new_str = new_str.replace(b, '+')
print(new_str)
10.輸入字符串,獲取字符串的中間字符。例如: 輸入'abc1234' 輸出:'1' 輸入'abc123' 輸出'c1'
str1 = 'abcd123456'
n = len(str1)
if n % 2 ==0:
print(str1[n//2-1:n//2+1])
else:
print(str1[n//2])
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。