1.輸入一個(gè)字符串橱赠,打印所有奇數(shù)位上的字符(下標(biāo)是1,3箫津,5狭姨,7…位上的字符)
""" 例如: 輸入'abcd1234 ' 輸出'bd24' """
str1 = 'Nothing gonna change my love for you '
index = 0
for char in str1:
if index & 1:
print(char, end='')
index += 1
print('')
2.輸入用戶(hù)名,判斷用戶(hù)名是否合法(用戶(hù)名長(zhǎng)度6~10位)
count = 0
user_id = input('請(qǐng)輸入用戶(hù)名(長(zhǎng)度6~10位):')
for length in user_id:
count += 1
if 6 <= count <= 10:
print('恭喜您注冊(cè)成功苏遥!')
else:
print('用戶(hù)名不合法請(qǐng)重新輸入')
3.輸入用戶(hù)名饼拍,判斷用戶(hù)名是否合法(用戶(hù)名中只能由數(shù)字和字母組成)
user_id = input('Pls enter your user name:')
for char in user_id:
if not ('0' <= char <= '9' or 'a' <= char <= 'z' or 'A' <= char <= 'Z'):
print('Illegal')
else:
print('finished')
4.輸入用戶(hù)名,判斷用戶(hù)名是否合法(用戶(hù)名必須包含且只能包含數(shù)字和字母田炭,并且第一個(gè)字符必須是大寫(xiě)字母)
user_id = input('Pls enter your user name:')
if ('A' <= user_id[0] <= 'Z'):
for char in user_id:
if not ('0' <= char <= '9' or 'a' <= char <= 'z' or 'A' <= char <= 'Z'):
print('注冊(cè)失敗')
break
else:
print('成功遼')
else:
print('瓜娃')
"""
5.輸入一個(gè)字符串师抄,將字符串中所有的數(shù)字字符取出來(lái)產(chǎn)生一個(gè)新的字符串
例如:輸入'abc1shj23kls99+2kkk' 輸出:'123992'
"""
str1 = 'abc1shj23kls99+2kkk'
new_str = ''
for char in str1:
if '0' <= char <= '9':
new_str += ''.join(char)
print(new_str)
"""
6.輸入一個(gè)字符串,將字符串中所有的小寫(xiě)字母變成對(duì)應(yīng)的大寫(xiě)字母輸出 (用upper方法和自己寫(xiě)算法兩種方式實(shí)現(xiàn))
例如: 輸入'a2h2klm12+' 輸出 'A2H2KLM12+'
"""
# 方法一
str1 = 'a2h2klm12+'
print(str1.upper())
"""
7.輸入一個(gè)小于1000的數(shù)字教硫,產(chǎn)生對(duì)應(yīng)的學(xué)號(hào)
例如: 輸入'23'叨吮,輸出'py1901023' 輸入'9', 輸出'py1901009' 輸入'123',輸出'py1901123'
"""
num = input('請(qǐng)輸入一個(gè)小于1000的數(shù)字: ')
stu_num = num.zfill(3)
print('py1901%s' % stu_num)
"""
8.輸入一個(gè)字符串瞬矩,統(tǒng)計(jì)字符串中非數(shù)字字母的字符的個(gè)數(shù)
例如: 輸入'anc2+93-sj胡說(shuō)' 輸出:4 輸入'===' 輸出:3
"""
str = input('請(qǐng)輸入內(nèi)容:')
count = 0
for char in str:
normal = ('A' <= char <= 'Z') or ('a' <= char <= 'z')
if not normal and not char.isdigit():
count += 1
print('非數(shù)字字母的字符有%d個(gè)' % count)
"""
9.輸入字符串茶鉴,將字符串的開(kāi)頭和結(jié)尾變成'+',產(chǎn)生一個(gè)新的字符串
例如: 輸入字符串'abc123', 輸出'+bc12+'
"""
str1 = 'abc123'
new_str = str1.replace('a', '+')
new_str = new_str.replace('3', '+')
print(new_str)
"""
10.輸入字符串丧鸯,獲取字符串的中間字符
例如: 輸入'abc1234' 輸出:'1' 輸入'abc123' 輸出'c1'
"""
str1 = input('請(qǐng)輸入字符串:')
str_len = len(str1)
if str_len %2:
print(str1[str_len // 2])
else:
print(str[str_len//2-1] + str[str_len//2])
"""
11.寫(xiě)程序?qū)崿F(xiàn)字符串函數(shù)find/index的功能(獲取字符串1中字符串2第一次出現(xiàn)的位置)
例如: 字符串1為:how are you? Im fine, Thank you! , 字符串2為:you, 打印8
"""
str1 = 'how are you? Im fine, Thank you!'
str2 = 'you'
sign = str1.index(str2)
print('符串1中字符串2第一次出現(xiàn)的位置是:', sign)
"""
12.獲取兩個(gè)字符串中公共的字符
例如: 字符串1為:abc123, 字符串2為: huak3 , 打印:公共字符有:a3
"""
str1 = input('請(qǐng)輸入字符串1:')
str2 = input('輸入字符串2:')
common_part = ''.join(set(str1)&set(srt2))
print(common_part)