1. 輸入一個字符串,打印所有奇數(shù)位上的字符(下標是1,3,5,7…位上的字符)
例如: 輸入'abcd1234 ' 輸出'bd24'
str1 = input('輸入一個字符串:')
for index in range(len(str1)):
if index % 2 != 0:
print(index, str1[index])
print('************************************************')
2. 輸入用戶名,判斷用戶名是否合法(用戶名長度6~10位)
str2 = input('請輸入用戶名:')
if 6 <= len(str2) <= 10:
print('用戶名合法')
else:
print('不合法')
3. 輸入用戶名,判斷用戶名是否合法(用戶名中只能由數(shù)字和字母組成)
例如: 'abc' — 合法 '123' — 合法 ‘a(chǎn)bc123a’ — 合法
str3 = input('輸入用戶名:')
for item in str3:
if 'a' <= item <= 'z' or 'A' <= item <= 'Z' or '0' <= item <= '9':
print('合法ID')
break
else:
print('非法ID')
break
4. 輸入用戶名,判斷用戶名是否合法(用戶名必須包含且只能包含數(shù)字和字母,并且第一個字符必須是大寫字母)
例如: 'abc' — 不合法 '123' — 不合法 'abc123' — 不合法 'Abc123ahs' — 合法
str4 = input('輸入用戶名:')
for item in str4:
if 'a' <= item <= 'z' or 'A' <= item <= 'Z' or '0' <= item <= '9':
if 'A' <= str4[0] <= 'Z':
if '0' <= item <= '9':
print('合法ID')
break
else:
print('非法ID')
break
5. 輸入一個字符串,將字符串中所有的數(shù)字字符取出來產(chǎn)生一個新的字符串。
例如:輸入'abc1shj23kls99+2kkk' 輸出:'123992'
str5 = input('輸入字符串:')
for item in str5:
if '0' <= item <= '9':
print(item, end='')
6. 輸入一個字符串,將字符串中所有的小寫字母變成對應(yīng)的大寫字母輸出。
例如: 輸入'a2h2klm12+' 輸出 'A2H2KLM12+'
str6 = input('輸入字符串:')
print(str6.upper())
7. 輸入一個小于1000的數(shù)字,產(chǎn)生對應(yīng)的學號
例如: 輸入'23',輸出'py1901023' 輸入'9', 輸出'py1901009' 輸入'123',輸出'py1901123'
num = int(input('輸入一個小于1000的數(shù):'))
study_id = 'py1901' + str(num).rjust(3)
print(study_id)
8. 輸入一個字符串,統(tǒng)計字符串中非數(shù)字字母的字符的個數(shù)
例如: 輸入'anc2+93-sj胡說' 輸出:4 輸入'===' 輸出:3
str7 = input('輸入字符串:')
count = 0
for item in str7:
if '0' <= item <= '9' or 'a' <= item <= 'z' or 'A' <= item <= 'Z':
continue
else:
count += 1
print(count)
9. 輸入字符串,將字符串的開頭和結(jié)尾變成'+',產(chǎn)生一個新的字符串
例如: 輸入字符串'abc123', 輸出'+bc12+'
str8 = input('輸入字符串:')
new_str1 = str8.lstrip(str8[:1])
new_str2 = new_str1.rstrip(new_str1[:-2:-1])
new_str3 = new_str2.center(len(new_str2)+2, '+')
print(new_str3)
10. 輸入字符串,獲取字符串的中間字符
例如: 輸入'abc1234' 輸出:'1' 輸入'abc123' 輸出'c1'
str9 = input('輸入字符串:')
if len(str9) % 2 == 0:
print(str9[int(len(str9)/2-1)], str9[int(len(str9)/2)])
else:
print(str9[int(len(str9)/2)])